Next.js Discord

Discord Forum

What could be causing the token to always be null on the Vercel server?

Unanswered
rand posted this in #help-forum
Open in Discord
I'm using NextAuth along with Google as the authentication provider for my application.
To manage access, I've implemented authentication middleware, as shown below. Locally, the authentication token is present, allowing access to protected routes.
However, when deployed on Vercel, logs indicate that the token value is consistently null. As a result, despite having an active session, the application redirects to the root route.
I've verified the redirect URL, Google service configuration, and environment variables multiple times, so there appears to be no issues there.
What could be causing the token to always be null on the Vercel server?

import { getToken } from 'next-auth/jwt';
import { NextResponse } from 'next/server';
import type { NextRequest } from 'next/server';

export async function middleware(req: NextRequest) {
  const token = await getToken({ req, secret: process.env.NEXTAUTH_SECRET });
  console.log('##############middleware token#################', token)
  const { pathname } = req.nextUrl;

  // Bypass middleware for root, Next.js internal files, and API requests
  if (pathname === "/" || pathname.startsWith('/_next') || pathname.startsWith('/api')) {
    return NextResponse.next();
  }

  // If there's no token and the user is requesting a protected route, redirect to root
  if (!token) {
    const url = req.nextUrl.clone();
    url.pathname = '/';
    return NextResponse.redirect(url);
  }

  // Continue with the response for all other cases
  return NextResponse.next();
}

1 Reply

Anybody can help me out?