node.jscookiesaxiosjwtbackend

JWT Token/Cookies Not Sent from Frontend (Vercel) to Backend (Render) – Getting 401 Unauthorized


I'm a self-learning web developer, and I recently deployed my backend on Render (free tier) and my frontend on Vercel. The stack includes Node.js, Express, MongoDB, WebSockets, and authentication is handled via Passport.js (Google OAuth).

The Issue:

Expected Behavior:

What I Have Tried:

  1. Checked CORS Configuration (Backend - Render)

const options = {
httpOnly: true,
secure: isProduction,  // Secure in production
sameSite: "none",  // Required for cross-origin cookies
maxAge: 7 * 24 * 60 * 60 * 1000, // 7 days
};

app.use(
cors({
  origin: "https://sync-sphere-eight.vercel.app",  // Frontend URL
  credentials: true, // Allow credentials (cookies)
  methods: ["GET", "PUT", "POST", "DELETE", "OPTIONS"],
  allowedHeaders: [
    "Access-Control-Allow-Origin",
    "Content-Type",
    "Authorization",
    "Origin",
    "X-Requested-With",
    "Accept",
  ],
  exposedHeaders: ["Access-Control-Allow-Credentials"],
})
);

app.options("*", cors());
  1. Axios Config (Frontend - Vercel)

export const api = axios.create({
 baseURL: API_URL,
 withCredentials: true,  // Ensures cookies are sent with requests
});
  1. Checked Browser Cookies in DevTools:

    • Cookies are present in the browser after login.
    • However, they are not sent with API requests.
  2. Manually Tested with Postman (Works!)

    • When sending a request to my backend's protected route via Postman, it works perfectly!
    • The backend receives the cookies and validates the request.
  3. Problem causes?

    • Render's free tier blocking cross-origin cookies?
    • Vercel not forwarding credentials properly?
    • Misconfigured CORS settings?

How can I make sure the cookies (tokens) are sent properly in requests from Vercel (frontend) to Render (backend)?

If you want to replicate the problem here's the live link of frontend - frontend-deployed-link

Note: Since the backend is deployed on Render’s free tier, it might take 50 seconds to spin up if it's inactive

Edit: Tried on Microsoft edge browser for some reasons it's working there but not in my current browser (Brave)


Solution

  • Turning off the brave shields fixed it for me