Next Auth.js - I can't get token with getToken({req})

Viewed 2348

I can't get the token with getToken:

enter image description here

This variables are ok: NEXTAUTH_SECRET=secret NEXTAUTH_URL=http://localhost:3000

Here is my [...nextauth].js - I can do console.log(token) and it works well

import NextAuth from "next-auth";
import GoogleProvider from "next-auth/providers/google";

...
  jwt: {
    secret: process.env.JWT_SECRET,
    encryption: true,
  },
  secret: process.env.NEXTAUTH_SECRET,
  callbacks: {
    async redirect({ url, baseUrl }) {
      return Promise.resolve(url);
    },
    async jwt({ token, user, account, profile, isNewUser }) {
      return token;
    },
    async session({ session, user, token }) {
      return session;
    },
  },
});

API section (I think getToken doesnt work well):

import { getToken } from "next-auth/jwt";

const secret = process.env.NEXTAUTH_SECRET;

export default async (req, res) => {
  const token = await getToken({ req, secret, encryption: true });
  console.log(token);
  if (token) {
    // Signed in
    console.log("JSON Web Token", JSON.stringify(token, null, 2));
  } else {
    // Not Signed in
    res.status(401);
  }
  res.end();
};
2 Answers

This might be a bug in the function but the only way i got it to work was to use getToken to get the raw jwt token and then use jsonwebtoken package to verify and decode it

import { getToken } from "next-auth/jwt";
import jwt from "jsonwebtoken";
const secret = process.env.NEXT_AUTH_SECRET;
  const token = await getToken({
    req: req,
    secret: secret,
    raw: true,
  });
const payload = jwt.verify(token, process.env.NEXT_AUTH_SECRET);
console.log(payload);

this worked for me:

  const secret = process.env.SECRET
  const token = await getToken({ req:req ,secret:secret});

also check [...nextauth].js, if you're using

adapter: MongoDBAdapter(clientPromise),

then you dont have JWT token, you have to set

  session: {
    strategy: "jwt",
  },

notice this will save the session locally and not on the database

more info here: https://next-auth.js.org/configuration/options#session

Related