DEV Community

Cover image for Set up your authentication with Next.js and AWS Cognito
Fabien Townsend
Fabien Townsend

Posted on • Updated on

Set up your authentication with Next.js and AWS Cognito

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,
        },
      }
    );
Enter fullscreen mode Exit fullscreen mode

For the front-end, the following configuration using AWS Amplify is recommended:

"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)
Enter fullscreen mode Exit fullscreen mode

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.

Top comments (0)