0

I am using next js. I am using next-auth for authentication. it is a MERN stack project.

Question: How can I get jwt token and send it to my backend using next-auth and axios.

(session.jwt) is giving me undefined.

here is my nextauth.js file:

import NextAuth from 'next-auth';
import GoogleProvider from 'next-auth/providers/google';
import { MongoDBAdapter } from '@next-auth/mongodb-adapter';
import clientPromise from '../../../lib/mongodb';

export default NextAuth({
  providers: [
    GoogleProvider({
      clientId: process.env.GOOGLE_CLIENT_ID,
      clientSecret: process.env.GOOGLE_CLIENT_SECRET,
    }),
  ],
  callbacks: {
    session: async ({ session, user }) => {
      if (session?.user) {
        session.user.id = user.id;
      }
      return session;
    },
  },
  adapter: MongoDBAdapter(clientPromise),
  secret: process.env.JWT_SECRET,
  session: {
    jwt: true,
    maxAge: 30 * 24 * 60 * 60, // the session will last 30 days
  },
});
Sajib Hossain
  • 81
  • 2
  • 8

1 Answers1

5

The example in their docs persists the provider (account) access token in the jwt callback and then includes it to the session object:

  callbacks: {
    async jwt({ token, account }) {
        if (account) {
          token.accessToken = account.access_token;
        }
        return token;
      },    
    async session({ session, token, user }) {
      if (session?.user) {
        session.user.id = user.id;
      }
      return {
        ...session,
        accessToken: token.accessToken
      };
    },
  }

However, if you want the raw JWT (not the provider access token) and you're server side you can use the getToken function:

export async function getServerSideProps(context) {
  const token = await getToken({ req: context.req, raw: true });
// ...
}

Then to use it in your requests, here in the authorization header for example):

const config = {
    headers : {
        'Authorization' : `Bearer ${token}`
    }
}
axios.get('http://web.com/api', config);
makchamp
  • 81
  • 4
  • Hi. I am getting this error " "Cannot read properties of undefined (reading 'accessToken')". I am using google authentication. – Sajib Hossain Jan 24 '23 at 14:52
  • Is the session/jwt created properly ? I think in your [...nextauth].js it should be: session: { strategy: 'jwt', maxAge: 30 * 24 * 60 * 60 } // instead of jwt: true – makchamp Jan 25 '23 at 03:44
  • But jwt strategy should be by default. Maybe there is an issue with your adapter ? – makchamp Jan 25 '23 at 03:51
  • Unfortunately getToken() doesn't work in server components - there is not request there. – LeoD Jul 01 '23 at 10:43