0

I'm developping an app in mern stack using http only cookie request and while handling it in frontend it doesnt work but in postman it is working And here is the coode for generating token

import jwt from "jsonwebtoken";

const generateToken = (res, userId) => {
  const token = jwt.sign({ userId }, process.env.JWT_SECRET, {
    expiresIn: "10d",
  });

  res.cookie("jwt", token, {
    httpOnly: true,
    secure: true,
    sameSite: "none",
    maxAge: 10 * 24 * 60 * 60 * 1000,
  });
};

export default generateToken;

and here is the routes

import express from "express";
import {
  authUser,
  registerUser,
  logoutUser,
  getUserProfile,
  updateUserProfile,
} from "../controllers/userController.js";
import { protect } from "../middleware/authMiddleware.js";
const router = express.Router();

router.post("/auth", authUser);
router.post("/", registerUser);
router.post("/logout", logoutUser);
router
  .route("/profile")
  .get(protect, getUserProfile)
  .put(protect, updateUserProfile);

export default router;

and here is the server

import express from "express";
import dotenv from "dotenv";
import cookieParser from "cookie-parser";
import connectToDb from "./config/connectToDb.js";
import userRoutes from "./routes/userRoutes.js";
import { notFound, errorHandler } from "./middleware/errorMiddleware.js";
import cors from "cors";
import helmet from "helmet";

dotenv.config();

const port = process.env.PORT || 5000;

connectToDb();
const app = express();

app.use(helmet());
app.use(cors({ credentials: true }));
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
app.use(cookieParser());
app.use("/api/users", userRoutes);

app.get("/", (req, res) => {
  res.send("Server is ready");
});

app.use(notFound);
app.use(errorHandler);

app.listen(port, () => {
  console.log(`Server started at http://localhost:${port}`);
});

and here is the api call in frontend with redux

import { apiSlice } from "./apiSlice";

// Update the endpoint URL to localhost:5000
const USERS_URL = "/api/users";

export const usersApiSlice = apiSlice.injectEndpoints({
  endpoints: (builder) => ({
    login: builder.mutation({
      query: (data) => ({
        url: `${USERS_URL}/auth`,
        method: "POST",
        body: data,
      }),
    }),
    register: builder.mutation({
      query: (data) => ({
        url: `${USERS_URL}`,
        method: "POST",
        body: data,
      }),
    }),
    logout: builder.mutation({
      query: () => ({
        url: `${USERS_URL}/logout`,
        method: "POST",
      }),
    }),
    updateUser: builder.mutation({
      query: (data) => ({
        url: `${USERS_URL}/profile`,
        method: "PUT",
        body: data,
      }),
    }),
  }),
});

export const {
  useLoginMutation,
  useLogoutMutation,
  useRegisterMutation,
  useUpdateUserMutation,
} = usersApiSlice;

i ve tried to change to change the credentials in server.js and also and changer secure to true and the also changer the sameSite to none and problem in exsisting

  • If you're having trouble with this cookie in development when making requests from a `http` host (eg `http://localhost:3000`), then try changing this cookie setting to `secure: false`, but **FOR DEVELOPMENT ONLY**. By setting this as `secure: true`, it means you must make requests from a secure `https` host, otherwise the cookie isn't set by the browser. See [this](https://stackoverflow.com/questions/13729749/how-does-cookie-secure-flag-work) for more information. – Matt Carlotta Jul 20 '23 at 22:30
  • If that doesn't fix your problem, then I'd recommend inspecting the network response headers. For example, in your browser dev tools, there should be a "Network" tab. Inspect the "Response" headers for the specific request. You should see a `set-cookie` header. If you see that, then your browser is blocking it from being set. If not, you have a server-side configuration problem. – Matt Carlotta Jul 20 '23 at 22:42

1 Answers1

0

i solved it finally by adding the proxy to my react app

  • Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Jul 27 '23 at 14:55