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
👋 While you are here

Reinvent your career. Join DEV.

It takes one minute and is worth it for your career.

Get started

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

Engage with a sea of insights in this enlightening article, highly esteemed within the encouraging DEV Community. Programmers of every skill level are invited to participate and enrich our shared knowledge.

A simple "thank you" can uplift someone's spirits. Express your appreciation in the comments section!

On DEV, sharing knowledge smooths our journey and strengthens our community bonds. Found this useful? A brief thank you to the author can mean a lot.

Okay