Next.js Discord

Discord Forum

Auth.js creates ill formatted JWT tokens

Unanswered
Green Kingfisher posted this in #help-forum
Open in Discord
Green KingfisherOP
Here is my auth.ts file:

import NextAuth, { CredentialsSignin } from 'next-auth';
import Credentials from 'next-auth/providers/credentials';
import { PrismaAdapter } from '@auth/prisma-adapter';
import { prisma } from '@/lib/prisma';
import { compare } from 'bcryptjs';
import authConfig from '@/auth.config';
import github from 'next-auth/providers/github';

const secret = new TextEncoder().encode(process.env.JWT_SECRET || '');

export const { handlers, signIn, signOut, auth } = NextAuth({
  adapter: PrismaAdapter(prisma),
  session: { strategy: 'jwt' },
  ...authConfig,
  pages: {
    signIn: '/sign-in',
    signOut: '/sign-out',
  },
  providers: [
    github,
    Credentials({
      credentials: {
        email: {},
        password: {},
      },
      authorize: async (credentials) => {
        // logic to check user details in db and return it
      }
  ],
  callbacks: {
    authorized({ request: { nextUrl }, auth }) {
      const isLoggedIn = !!auth?.user;
      const { pathname } = nextUrl;

      if (!isLoggedIn && (pathname.startsWith('/sign-in') || pathname.startsWith('/sign-up'))) {
        return true;
      }

      if (isLoggedIn && (pathname.startsWith('/sign-in') || pathname.startsWith('/sign-up'))) {
        return Response.redirect(new URL('/', nextUrl));
      }

      return !!auth;
    },
    async jwt({ token, user }) {
      if (user) {
        token.id = user.id;
      }

      return token;
    },
  },
  cookies: {
    sessionToken: {
      name: 'token',
      options: {
        httpOnly: true,
        sameSite: 'lax',
        path: '/',
      },
    },
  },
});

Creating a JWT token, sending it as httpOnly cookie. I also have a custom backend using ExpressJs where im decoding the token using jsonwebtoken package but it returns jwt malformed error.

JWT has this format:
[payload].[header].[signature]

But the generated JWT token has:
[payload]..[signature]


How to fix this?

0 Replies