CORS issue between Next.js frontend (Vercel) and Express backend on JWT authentication (Render) in production

I've been struggling with a CORS issue for weeks while working on my application. Everything works fine locally, but when I test it in production, the requests from my frontend (hosted on Vercel) to my backend (hosted on Render) are blocked by CORS.

Tech Stack: Frontend: Next.js (hosted on Vercel) Backend: Node.js/Express (hosted on Render, using JWT for access and refresh token authentication)

Problem: In production, the browser blocks the requests with the following error: Access to XMLHttpRequest at 'https://ai-pulse-backend.onrender.com/api/v1/auth/login' from origin 'https://ai-pulse-frontend.vercel.app' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

`Sometimes, I also see:
CORS request did not succeed. Status code: (null)

What I’ve Tried:`

Configured CORS middleware in Express using the cors package. Allowed the Vercel domain (https://ai-pulse-frontend.vercel.app) in the CORS configuration. Tested adding additional headers like Authorization and Content-Type on both frontend and backend. Ensured withCredentials: true is used on both sides for cookies. Tested API endpoints with tools like Postman (works fine). Tried adding headers on the frontend with fetch and axios.

Here is my current CORS setup in the Express backend:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>import express, { Request, Response, NextFunction } from "express";
import cors from "cors";
import cookieParser from "cookie-parser";
import routes from "./routes/index";
const app = express();
const port = process.env.PORT || 8080;
const corsOptions = {
origin: ["http://localhost:3000", "https://ai-pulse-frontend.vercel.app"], // Replace with your frontend URL
credentials: true, // Allow server to accept cookies
methods: ["GET", "POST", "PUT", "DELETE", "OPTIONS"],
allowedHeaders: ["Content-Type", "Authorization"],
};
app.use(cors(corsOptions)); // Enable CORS
app.use(express.json()); // Parse incoming JSON requests
app.use(cookieParser()); // Parse cookies
app.use((req: Request, res: Response, next: NextFunction) => {
const origin = req.headers.origin;
if (origin && corsOptions.origin.includes(origin)) {
res.header("Access-Control-Allow-Origin", origin);
}
res.header("Access-Control-Allow-Credentials", "true");
res.header("Access-Control-Allow-Methods", "GET,HEAD,PUT,PATCH,POST,DELETE,OPTIONS");
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept, Authorization");
if (req.method === "OPTIONS") {
res.status(200).end();
return;
}
next();
});
app.use(routes);
app.get("/", (req: Request, res: Response) => {
res.status(200).send("API is running...");
});
app.listen(port, () => {
console.log(`Server is running on port ${port}`);
});
</code>
<code>import express, { Request, Response, NextFunction } from "express"; import cors from "cors"; import cookieParser from "cookie-parser"; import routes from "./routes/index"; const app = express(); const port = process.env.PORT || 8080; const corsOptions = { origin: ["http://localhost:3000", "https://ai-pulse-frontend.vercel.app"], // Replace with your frontend URL credentials: true, // Allow server to accept cookies methods: ["GET", "POST", "PUT", "DELETE", "OPTIONS"], allowedHeaders: ["Content-Type", "Authorization"], }; app.use(cors(corsOptions)); // Enable CORS app.use(express.json()); // Parse incoming JSON requests app.use(cookieParser()); // Parse cookies app.use((req: Request, res: Response, next: NextFunction) => { const origin = req.headers.origin; if (origin && corsOptions.origin.includes(origin)) { res.header("Access-Control-Allow-Origin", origin); } res.header("Access-Control-Allow-Credentials", "true"); res.header("Access-Control-Allow-Methods", "GET,HEAD,PUT,PATCH,POST,DELETE,OPTIONS"); res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept, Authorization"); if (req.method === "OPTIONS") { res.status(200).end(); return; } next(); }); app.use(routes); app.get("/", (req: Request, res: Response) => { res.status(200).send("API is running..."); }); app.listen(port, () => { console.log(`Server is running on port ${port}`); }); </code>
import express, { Request, Response, NextFunction } from "express";
import cors from "cors";
import cookieParser from "cookie-parser";
import routes from "./routes/index";

const app = express();
const port = process.env.PORT || 8080;
 
const corsOptions = {
  origin: ["http://localhost:3000", "https://ai-pulse-frontend.vercel.app"], // Replace with your frontend URL
  credentials: true, // Allow server to accept cookies
  methods: ["GET", "POST", "PUT", "DELETE", "OPTIONS"],
  allowedHeaders: ["Content-Type", "Authorization"],
};

app.use(cors(corsOptions)); // Enable CORS
app.use(express.json()); // Parse incoming JSON requests
app.use(cookieParser()); // Parse cookies


app.use((req: Request, res: Response, next: NextFunction) => {
  const origin = req.headers.origin;
  if (origin && corsOptions.origin.includes(origin)) {
    res.header("Access-Control-Allow-Origin", origin);
  }
  res.header("Access-Control-Allow-Credentials", "true");
  res.header("Access-Control-Allow-Methods", "GET,HEAD,PUT,PATCH,POST,DELETE,OPTIONS");
  res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept, Authorization");

  if (req.method === "OPTIONS") {
    res.status(200).end();
    return;
  }

  next();
});


app.use(routes);

app.get("/", (req: Request, res: Response) => {
  res.status(200).send("API is running...");
});


app.listen(port, () => {
  console.log(`Server is running on port ${port}`);
});

Here is how I set up Axios on the frontend with withCredentials:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>import axios from "axios";
const BASE_URL = "https://ai-pulse-backend.onrender.com/api/v1";
const api = axios.create({
baseURL: BASE_URL,
withCredentials: true,
});
export default api;
</code>
<code>import axios from "axios"; const BASE_URL = "https://ai-pulse-backend.onrender.com/api/v1"; const api = axios.create({ baseURL: BASE_URL, withCredentials: true, }); export default api; </code>
import axios from "axios";

const BASE_URL = "https://ai-pulse-backend.onrender.com/api/v1";

const api = axios.create({
  baseURL: BASE_URL,
  withCredentials: true,
});

export default api;

I also use zustand to manage authentication:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>login: async (email: string, password: string) => {
const response = await api.post("/auth/login", { email, password });
const { accessToken } = response.data;
api.defaults.headers.common["Authorization"] = `Bearer ${accessToken}`;
}
</code>
<code>login: async (email: string, password: string) => { const response = await api.post("/auth/login", { email, password }); const { accessToken } = response.data; api.defaults.headers.common["Authorization"] = `Bearer ${accessToken}`; } </code>
login: async (email: string, password: string) => {
  const response = await api.post("/auth/login", { email, password });
  const { accessToken } = response.data;
  api.defaults.headers.common["Authorization"] = `Bearer ${accessToken}`;
}

`Questions:

How do I properly configure CORS for a Next.js frontend hosted on Vercel and an Express backend hosted on Render in production?
Are there additional headers or settings needed for JWT authentication over CORS?

Any guidance or solutions would be greatly appreciated!`

New contributor

Abubakar Muhammad Ala is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.

1

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật