0

I'm trying to setup a simple middleware for my backend that checks for cookies, authenticates (or not) and calls the next middleware function using react-cookie. I know I have to enable cookie-parser for my express and I've done that like so:

import express from "express";
import cookieParser from "cookie-parser";
import expenseRoutes from "./routes/expense.js";
import { authMiddleware } from "./middleware/authMiddleware.js";

dotenv.config();
const app = express();
app.use(cookieParser());

app.use("/expense", authMiddleware, expenseRoutes);

My frontend uses the useCookie hook from the react-cookie library like this:

  const [cookies] = useCookies(["id"]);
  const { data: expenses, isLoading } = useGetExpensesQuery(cookies.id);

And it works in the sense that cookies are saved and persist on browser close/reload. So the frontend is fine, problem is, I'm putting the cookie id as a query string in my dispatch:

const { data: expenses, isLoading } = useGetExpensesQuery(cookies.id);

This was a temporary solution to get the frontend working. Now I'd like to make a backend middleware to scan for cookies with each request and go from there, but when I console log req.cookies in my middleware, I get an empty object:

import jwt from "jsonwebtoken";
import User from "../models/User.js";
import { useCookies } from "react-cookie";

export const authMiddleware = async (req, res, next) => {
  console.log(req.cookies);
  next();
};

Empty object:

[Object: null prototype] {}

I'm setting credentials to 'include' in my API like so:

deleteExpense: build.mutation<Expense[], string>({
    query: (id) => ({
        url: `expense/expenses/${id}`,
        method: 'DELETE',
        credentials: 'include'
    })
}),

And both backend and frontend are running locally on the same port

I'm not sure why the backend can't pick up on the cookies, very possible I'm not understanding something, any ideas?

Mathew
  • 318
  • 11

1 Answers1

0

These are all the changes I made, it works now:

I added credentials: 'include' to both my API:

baseQuery: fetchBaseQuery({baseUrl: 'http://localhost:1337', credentials: 'include'}),

And my express server:

app.use(cors({ origin: "http://localhost:5173", credentials: true }));

I'm still not sure why I need to do it on my backend, if anyone can explain

Mathew
  • 318
  • 11