admin管理员组

文章数量:1123000

I am encountering a bug in my public deployment that does not occur in my local deployment. When users enter correct login info and press the button, a cookie is created to grant them access to the main pages of the website. In my local development environment, where both the frontend and backend run on localhost but on different ports (frontend on http://localhost:3000 and backend on http://localhost:5000), everything works as expected.

When deployed, to vercel and render for the front and backend respectively, my middleware reads the token as empty and redirects the user back to the login page. In the network tab on the login page, you can see loggedin which will confirm for you that you are logged in.

By going to the website, you can recreate this bug with the following info

username: [email protected]

password: password

Here is my Github repo with some additional information and the source code. I will paste relevant code below as well.

The options I am using with CORS:

const corsOptions = {
    origin: process.env.NODE_ENV === 'production'
        ? [process.env.FRONTEND_URL]  // Production frontend URL
        : ['http://localhost:3000'],  // Development URL
    credentials: true,
    methods: ['GET', 'POST', 'PUT', 'DELETE', 'OPTIONS', 'PATCH'],
    allowedHeaders: [
        'Content-Type',
        'Authorization',
        'X-Requested-With',
        'Accept',
        'Cookie'
    ],
    exposedHeaders: ['Set-Cookie'],
    maxAge: 86400
};

My middleware.js file that is responsible for the redirection:

import { NextResponse } from 'next/server';

export function middleware(request) {
  
  const path = request.nextUrl.pathname;
  const isPublicPath = path === '/login' || path === '/register' || path === '/forgot-password';
  
  // Get token with more detailed error handling
  const token = request.cookies.get('token')?.value;
  console.log('Token Value:', token);
  
  if (!isPublicPath && !token) {
    console.log('Redirecting to login - No token found');
    return NextResponse.redirect(new URL('/login', request.url));
  }

  return NextResponse.next();
}

// Ensure middleware runs on all relevant paths
export const config = {
  matcher: [
    '/login',
    '/register',
    '/forgot-password',
    '/dashboard/:path*'
  ]
};

Please feel free to ask clarifying questions.

本文标签: jwtMiddleware cannot access cookies set on frontend domainStack Overflow