Next.js Discord

Discord Forum

NextAuth Store and Access JWT

Unanswered
AM posted this in #help-forum
Open in Discord
AMOP
Hello, i do have created NextAuth with few providers and everything works fine but i do have issues reading the JWT that is passed from custom backend to me after succesfully login.

This is the CustomProvider implementation:

CredentialsProvider({
      name: 'Credentials',
      credentials: {
        email: {
          label: 'Email',
          type: 'email',
          placeholder: 'example@gmail.com',
          value: 'register_email@abv.bg'
        },
        password: {
          label: 'Password',
          type: 'password',
          value: 'register_password_123456'
        }
      },
      async authorize(credentials, req) {
        if (!credentials?.email || !credentials.password) {
          return null;
        }

        const response = await fetch(baseUrl, {
          method: 'POST',
          body: JSON.stringify({
            email: credentials.email,
            password: credentials.password
          }),
          headers: { 'Content-Type': 'application/json' }
        });

        const respData = await response.json();

        if (response.ok && respData.data.accessToken) {
          return respData.data;
        }

        return null;
      }
    })

respData.data.accessToken - contains server JWT

And then i'm trying to create a middleware that will read the token and apply it as a Authorization header

middleware.ts

// Without a defined matcher, this one line applies next-auth

import { NextMiddleware, NextRequest, NextResponse } from 'next/server';

// to the entire project
export { default } from 'next-auth/middleware';

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

export const middleware: NextMiddleware = async (req) => {
  const token = await getToken({ req });
  console.log('token', token);
};

export const config = { matcher: ['/extra'] };


but this is what i get from the log of the token:

token {
  iat: 1698234422,
  exp: 1700826422,
  jti: '9af2c7bc-00a8-446d-9d2c-04b14acff1c5'
}

2 Replies

AMOP
Any ideas what i'm doing wrong and is it correct this approach at all? How to get the jwt that is returned from my server and then set it as a Authorization: Bearer {jwt} header in the request. Thanks in advance! 🚀
AMOP
Oh i think i found out a solution, adding these callbacks:

  callbacks: {
    async jwt({ token, user }) {
      return { ...token, ...user };
    },
    async session({ session, token }) {
      session.user = token;

      return session;
    }
  }


now succesfully can read accessToken provided by the custom server in other places 🙏