Set up your authentication with Next.js and AWS Cognito
Tags: cdk, cws, cognito, nextjs
Published: 2023-11-19 12:25:37

---
title: Set up your authentication with Next.js and AWS Cognito
published: true
description: A quick authentication setup that uses Next.js, AWS Cognito, AWS CDK, and host Next.js on Vercel
tags: #cdk, #cws, #cognito, #nextjs
cover_image: https://dev-to-uploads.s3.amazonaws.com/uploads/articles/vacg349avstint1iqu3o.png
# Use a ratio of 100:42 for best results.
# published_at: 2023-11-16 10:28 +0000
---


In the realm of Next.js applications hosted on Vercel with an AWS infrastructure, establishing robust authentication becomes a pivotal task. After careful consideration of various options, including an in-house solution, Auth0, and Clerk, the decision was made to leverage AWS Cognito due to its seamless integration with AWS services.

The journey began with a glance at the existing in-house implementation, which fell short in handling advanced features such as email confirmation and password reset. While Auth0 and Clerk were considered, concerns about pricing and specific requirements like HIPAA compliance led to the selection of AWS Cognito.

Despite AWS Cognito's reputation for complex documentation, the benefits of integration with API Gateway and AppSync made it an attractive choice. The AWS CDK file presented below outlines the crucial steps in configuring AWS Cognito:
```
// *-stack.ts
    const userPool = new cognito.UserPool(this, "MyUserPool", {
      userPoolName: "my-next-auth-app-user-pool",
      selfSignUpEnabled: true,
      signInAliases: { email: true },
    });

    userPool.addDomain("MyUserPoolDomain", {
      cognitoDomain: {
        domainPrefix: "my-custom-domain-prefix",
      },
    });

    new cognito.UserPoolClient(
      this,
      "MyUserPoolClient",
      {
        userPool,
        userPoolClientName: "my-next-auth-app-client",
        authFlows: {
          userSrp: true,
          userPassword: true,
        },
      }
    );
```

For the front-end, the following configuration using AWS Amplify is recommended:
``` javascript
"use client";

import "@aws-amplify/ui-react/styles.css";
import { Amplify } from "aws-amplify";
import type { WithAuthenticatorProps } from "@aws-amplify/ui-react";
import { withAuthenticator } from "@aws-amplify/ui-react";

Amplify.configure({
  Auth: {
    Cognito: {
      userPoolId: "your user pool id",
      userPoolClientId: "your user pool client id",
      signUpVerificationMethod: "code",
      loginWith: {
        oauth: {
          domain:
            "you domain",
          scopes: [
            "phone",
            "email",
            "profile",
            "openid",
            "aws.cognito.signin.user.admin",
          ],
          redirectSignIn: ["http://localhost:3000/"],
          redirectSignOut: ["http://localhost:3000/"],
          responseType: "code", // or 'token', note that REFRESH token will only be generated when the responseType is code
        },
      },
    },
  },
});

const currentConfig = Amplify.getConfig();
Amplify.configure(currentConfig);
function App({ signOut, user }: WithAuthenticatorProps) {
  return (
    <>
      <h1>Hello {user?.username}</h1>
      <button onClick={signOut}>Sign out</button>
    </>
  );
}

export default withAuthenticator(App)
```

In conclusion, while this implementation serves as an illustrative example rather than a production-ready solution, it fills a void in resources for those seeking guidance on "AWS CDK + Next.js + Cognito." It's worth noting that the provided approach utilizes Amplify's configuration and UI for the login flow without relying on their CLI.