Search code examples
oauth-2.0next.jsamazon-cognito

Get JWT token in NextJS API


I created a NextJS application integrated with Amazon Cognito. I have a landing page that is using the Amplify Auth API (not the components). Now I need to call an external API to do CRUD operations. What's the best way to do this in NextJS?

I'm thinking I'll create an API in NextJS that will forward the request to the actual external REST API. But my problem is I'm not able to get the JWT Token on the API, since it's a backend code.

A code like this:

Auth.currentSession().then(data => console.log(data.accessToken.jwtToken));

Obviously won't work:

[DEBUG] 20:42.706 AuthClass - Getting current session
[DEBUG] 20:42.706 AuthClass - Failed to get user from user pool
[DEBUG] 20:42.707 AuthClass - Failed to get the current user No current user
(node:20724) UnhandledPromiseRejectionWarning: No current user

How can I get the token in the API?


Solution

  • I have resolved this problem by using the aws-cognito-next library.

    Following the documentation from https://www.npmjs.com/package/aws-cognito-next, I have created an auth utility:

    import { createGetServerSideAuth, createUseAuth } from "aws-cognito-next";
    import pems from "../../pems.json"
    
    // create functions by passing pems
    export const getServerSideAuth = createGetServerSideAuth({ pems });
    export const useAuth = createUseAuth({ pems });
    
    // reexport functions from aws-cognito-next
    export * from "aws-cognito-next";
    

    The pem file was generated by issuing the command (needless to say, you must configure an Amazon Cognito service first):

    yarn prepare-pems --region <region> --userPoolId <userPoolId>
    

    And finally, in the NextJs API:

    import {getServerSideAuth} from "../../src/utils/AuthUtils"
    
    export default async (req, res) => {
    
      const initialAuth = getServerSideAuth(req)
    
      console.log("initialAuth ", initialAuth)
    
      if (initialAuth) {
        res.status(200).json({status: 'success'})
    
      } else {
        res.status(400).json({status: 'fail'})
      }
    }