Search code examples
typescriptnext.jsamazon-cognitoaws-amplifynext.js13

Authentication routing with NextJS and AWS Amplify


After spending days of research, I can't really figure out how to handle the authentication routing with NextJS and AWS Amplify. This is the first time I'm using NextJS and I want to disable the login/register page for logged in users and disable the dashboard for not logged in users.

I already tried to check if user is authenticated with the AUTH api inside a middleware file but this didn't work. Searching on Google also didn't help because I wastn't be able to find anything related to this.

Hope someone can help me out.


Solution

  • Assuming you can successfully get a user info back from AWS Cognito (meaning you've configured your Amplify Cognito access properly), you need to use React Context Provider to have auth user information accessible for the whole app. Then, create some kinda route guard component and wrap your main app component in it.