Next.js Discord

Discord Forum

NextJs Auth middleware does not support Node.js 'crypto' module.

Unanswered
Prairie yellowjacket posted this in #help-forum
Open in Discord
Prairie yellowjacketOP
I have custom jwt encode and decode function which work fine outside the middleware, in middleware it doesn't let me use Node.js crypto module to decode my token, is there any workaround for this?
import Credentials from 'next-auth/providers/credentials';
import Facebook from 'next-auth/providers/facebook';
import Google from 'next-auth/providers/google';
import jwt from 'jsonwebtoken';

import type { NextAuthConfig } from 'next-auth';

export default {
    secret: process.env.TOKEN_SECRET,
    jwt: {
        maxAge: 30 * 24 * 60 * 60,
        encode: async (data: any) => {
            const { secret, token, maxAge } = data;
            const jwtClaims = {
                email: token.email,
                sub: token.sub ? token.sub : token.id,
                name: token.name,
                username: token.username,
                emailVerified: token.emailVerified,
                role: token.role,
                type: token.type,
                image: token.image
            };
            const expires_in = 15 * 60;
            const encodedToken = jwt.sign(jwtClaims, secret, {
                expiresIn: `${expires_in}s`,
                algorithm: 'HS256'
            });
            console.log('encodedToken', encodedToken);
            return encodedToken;
        },
        decode: async (data: any) => {
            console.log('decode', { data });
            const { secret, token, maxAge } = data;

            const verify = jwt.verify(token, secret, {
                algorithms: ['HS256']
            }) as any;
            console.log('verify', verify);
            return { ...verify, token };
        }
    }
} satisfies NextAuthConfig;

4 Replies

Prairie yellowjacketOP
middleware.ts
import NextAuth from 'next-auth';

import authConfig from '@/auth.config';
import { DEFAULT_LOGIN_REDIRECT, apiAuthPrefix, authRoutes, publicRoutes } from '@/routes';

const { auth } = NextAuth(authConfig);

export default auth((req: any) => {
    const { nextUrl } = req;
    const isLoggedIn = !!req.auth;
    // console.log('middleware', nextUrl.pathname);

    const isApiAuthRoute = nextUrl.pathname.startsWith(apiAuthPrefix);
    const isPublicRoute = publicRoutes.includes(nextUrl.pathname);
    const isAuthRoute =
        authRoutes.includes(nextUrl.pathname) || nextUrl.pathname.startsWith('/auth/reset-password/');

    if (isApiAuthRoute) {
        return null;
    }

    if (isAuthRoute) {
        if (isLoggedIn) {
            return Response.redirect(new URL(DEFAULT_LOGIN_REDIRECT, nextUrl));
        }
        return null;
    }

    if (!isLoggedIn && !isPublicRoute) {
        let callbackUrl = nextUrl.pathname;
        if (nextUrl.search) {
            callbackUrl += nextUrl.search;
        }

        const encodedCallbackUrl = encodeURIComponent(callbackUrl);

        return Response.redirect(new URL(`/auth/login?callbackUrl=${encodedCallbackUrl}`, nextUrl));
    }

    return null;
});

// Optionally, don't invoke Middleware on some paths
export const config = {
    matcher: ['/((?!.+\\.[\\w]+$|_next).*)', '/', '/(api|trpc)(.*)']
};
Prairie yellowjacketOP
when I do that it gives me this error
[auth][error] JWTSessionError: Read more at https://errors.authjs.dev#jwtsessionerror
[auth][cause]: JWEInvalid: Invalid Compact JWE
it's not using correct decode function now