DEV Community

Cover image for Cookies auto clearing after browser refresh issue , CORS related express cookies issue
Dennis kinuthia
Dennis kinuthia

Posted on

Cookies auto clearing after browser refresh issue , CORS related express cookies issue

This error is a combination of CORS issues and incorrect cookie settings.
To resolve you need to set your server to allow cookies and set the same origin policy to allow the frontend to make requests to your backend server.

cors

// cors-utils.ts
import type { Request, Response, NextFunction } from "express";

export function corsHeaders(req: Request, res: Response, next: NextFunction) {
  if (!req.headers.origin) return next();
  if (allowedOrigins.includes(req.headers.origin)) {
    res.setHeader("Access-Control-Allow-Credentials", "true");
    res.setHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE");
    next();
  }
}
export const allowedOrigins = [
  "http://localhost:3000",
  process.env.FRONTEND_URL ?? "",
];
Enter fullscreen mode Exit fullscreen mode
//  app.ts
app.use(corsHeaders);
app.use(
  cors({
    origin: (origin, callback) => {
      if ((origin && allowedOrigins.indexOf(origin) !== -1) || !origin) {
        callback(null, true);
      } else {
        callback(new Error("Not allowed by CORS"));
      }
    },
    optionsSuccessStatus: 200,
  }),
);
Enter fullscreen mode Exit fullscreen mode

and create the cookies using the options

import jwt from "jsonwebtoken";
const { sign, verify } = jwt;

const accessTokencookieOptions = {
      httpOnly: true,
      secure:true,
      sameSite: "none",
      path: "/",
      maxAge: 12 * 60 * 1000, // expires in 12 minutes
}

const accessTokebCookieKey = "rfsh-token";
  const fiftenMinutesInSeconds = Math.floor(Date.now() / 1000) + 60 * 15; // 15 minutes
  const accessToken = await sign(
    { ...sanitizedPayload, exp:  : fiftenMinutesInSeconds },
    ACCESS_TOKEN_SECRET,
  );
  res.clearCookie(accessTokebCookieKey, accessTokencookieOptions);
  res.cookie(accessTokebCookieKey, accessToken, accessTokencookieOptions);
Enter fullscreen mode Exit fullscreen mode

Heroku

Simplify your DevOps and maximize your time.

Since 2007, Heroku has been the go-to platform for developers as it monitors uptime, performance, and infrastructure concerns, allowing you to focus on writing code.

Learn More

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Immerse yourself in a wealth of knowledge with this piece, supported by the inclusive DEV Community—every developer, no matter where they are in their journey, is invited to contribute to our collective wisdom.

A simple “thank you” goes a long way—express your gratitude below in the comments!

Gathering insights enriches our journey on DEV and fortifies our community ties. Did you find this article valuable? Taking a moment to thank the author can have a significant impact.

Okay