I have the following config for my express server:
import express from "express";
import bodyParser from "body-parser";
import mongoose from "mongoose";
import cors from "cors";
import dotenv from "dotenv";
import helmet from "helmet";
import morgan from "morgan";
import cookieParser from "cookie-parser";
import categoryRoutes from "./routes/category.js";
import subCategoryRoutes from "./routes/subCategory.js";
import expenseRoutes from "./routes/expense.js";
import userRoutes from "./routes/user.js";
import { authMiddleware } from "./middleware/authMiddleware.js";
dotenv.config();
const app = express();
app.use(cookieParser());
app.use(express.json());
app.use(helmet());
app.use(helmet.crossOriginResourcePolicy({ policy: "cross-origin" }));
app.use(morgan("common"));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(
cors({
origin: *********************,
credentials: true,
})
);
app.use("/category", authMiddleware, categoryRoutes);
app.use("/subCategory", authMiddleware, subCategoryRoutes);
app.use("/expense", authMiddleware, expenseRoutes);
app.use("/user", userRoutes);
const PORT = process.env.PORT || 9000;
mongoose
.connect(process.env.MONGO_URL, {
useNewUrlParser: true,
useUnifiedTopology: true,
})
.then(async () => {
app.listen(PORT, () => {
console.log(`Server running on port: ${PORT}`);
});
})
.catch((error) => {
console.log(`${error} connecting to DB`);
});
But for any route that’s not "/user", I’m getting a "CORS Missing Allow Credentials" error with the following request headers:
Accept
*/*
Accept-Encoding
gzip, deflate, br
Accept-Language
en-US,en;q=0.5
Connection
keep-alive
Cookie
jwt=*************************
Host
*************************
Origin
https://*********************
Referer
https:/**********************/
Sec-Fetch-Dest
empty
Sec-Fetch-Mode
cors
Sec-Fetch-Site
cross-site
TE
trailers
User-Agent
Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:109.0) Gecko/20100101 Firefox/115.0
I am using a middleware for the other routes so maybe that might be causing an issue,
if so, here it is:
import jwt from "jsonwebtoken";
export const authMiddleware = async (req, res, next) => {
const { id, token } = req.cookies;
console.log(id, token);
try {
if (id) {
req.userId = id;
res.setHeader(
"Access-Control-Allow-Origin",
"**************************"
);
res.setHeader("Access-Control-Allow-Credentials", true);
next();
}
if (token) {
const decoded = jwt.verify(token, process.env.JWT_SECRET);
if (decoded) {
const userId = decoded.id;
req.userId = userId;
res.setHeader(
"Access-Control-Allow-Origin",
"**************************"
);
res.setHeader("Access-Control-Allow-Credentials", true);
next();
}
}
} catch (error) {
throw new Error("Not authorized!");
}
};
I’m thinking my cors and helmet configs are incorrectly setup but here is one of the endpoints I hit, I don’t have any headers set on it’s response:
router.get("/expenses/", async (req, res) => {
const userId = req.userId;
console.log(userId);
try {
const expenses = await Expense.find({
userId: userId,
})
.populate("subCategory")
.populate("category")
.exec();
const mappedExpenses = expenses.map((expense) => ({
id: expense._id,
date: expense.date,
price: expense.price,
userId: expense.userId,
category: expense.category.name,
subCategory: expense.subCategory.name,
}));
console.log("user expenses: ", mappedExpenses);
res.status(200).json(mappedExpenses);
} catch (error) {
res.status(404).json({ message: error.message });
}
});
It might be useful to add that the I’m getting a 502 bad gateway on the /expense/expenses request and a referrer policy of strict-origin-when-cross-origin
Lastly, I’m using rtk query to make these api calls with the following basequery:
baseQuery: fetchBaseQuery({baseUrl: import.meta.env.VITE_BASE_URL, credentials: 'include'}),
The env var matches the server url so no issue there and the frontend login component sets cookies like so:
loginUser(values)
.unwrap()
.then((res) => {
console.log(res._id);
setCookie("id", res._id, {
path: "/",
sameSite: "none",
secure: true,
});
toast.success("logged in!");
navigate("/dashboard", { replace: true });
})
.catch((e) => {
console.log(e);
});
2
Answers
Happy to report I spent 10 hours to only find in the end that the cookie I was setting on login was "jwt" and I was searching for a cookie named "token" in my middleware.
I am not quite sure about it but it might have something to with setting the cookie to secure.
In this case, you should not have * as allowed origin. I think configuring cors might fix it.
allowedOrigin.js:
corsOptions.js:
In the index/server.js file
NOT SURE ABOUT IT. JUST AN INTUITION.