Gbr
Gbr

Reputation: 105

Browser doesn't set cookies received from backend

I'm making a project which consist of:

Client and Server and hosted on two different domain.

I have accounts management system (logging / registering) which uses express-session and it needs to store sessionID in the client cookie. Everything was fine when I was testing it on localhost. But when I deployed it on hosting I can't make session to work. The problem is that browser receives set-session in response from server, but it doesn't set it in browser. I've spend many hours trying to fix it, reading about cors and cookies, but I'm completely lost.

This is my server configuration:

      app.use(session({
    name: 'session-cookie',
    secret: 'my-secret-key',
    resave: false,
    saveUninitialized: true,
    cookie: {
      httpOnly: false, // I tried both true and false - doesnt matter
      secure: (process.env.NODE_ENV == "DEPLOY"),
      sameSite: (process.env.NODE_ENV == "DEPLOY")? 'None':'Lax',
      domain: (process.env.NODE_ENV == "DEPLOY")? process.env.FRONT_URL.replace('https://', '') : undefined
    }
  }));

  app.use(
    cors({
      origin: (process.env.NODE_ENV == "DEPLOY")? process.env.FRONT_URL :'*' ,
      credentials: true, // Access-Control-Allow-Credentials (cookies)
    })
  );

  app.set('trust proxy', 1);

This is my client configuration when fetching (it fetches GET and POST requests):

function fetchAPI (api_url,data){
    const options = (api_url.method === "POST")?
    {
        method: "POST",
        body: JSON.stringify(data),
        headers: {
          "Content-type": "application/json; charset=UTF-8"
        },
        credentials: 'include'
      }
      :{
        method: "GET",
        credentials: 'include'
      }


    return fetch(api_url.url, options     
    ).then((response) => { 
        if (!response.ok) {
            throw new Error("Network did not respond!");
        }
        return response.json();
    })
    .catch((error) => {
        console.error('Error fetching API:', error);
    });
}

Example POST request headers: Response: (as you see it sends set-cookie)

HTTP/2 200 
date: Sun, 17 Nov 2024 10:21:00 GMT
content-type: application/json; charset=utf-8
content-length: 43
cf-ray: 8e3efdc8eb033bbf-WAW
cf-cache-status: DYNAMIC
access-control-allow-origin: https://front-end-client.netlify.app
content-encoding: br
etag: W/"27-bu5Ogz2a8jO3ftOvJz7bvL0wXFc"

set-cookie: session-cookie=s%3AM-rccgHt_RGQyWfbIGrE_qyoWl_Sb1BU.zwMbyHDogXN31prfcisOOF%2BDuVBjAOZJ11uqLsiNqAo;
Domain=front-end-client.netlify.app; Path=/; Secure; SameSite=None

vary: Origin, Accept-Encoding
access-control-allow-credentials: true
rndr-id: 63e2a4b5-5185-4d1a
x-powered-by: Express
x-render-origin-server: Render
server: cloudflare
alt-svc: h3=":443"; ma=86400
X-Firefox-Spdy: h2

Request:

POST /api/login HTTP/2
Host: back-end-client.onrender.com
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:132.0) Gecko/20100101 Firefox/132.0
Accept: */*
Accept-Language: en-US,en;q=0.5
Accept-Encoding: gzip, deflate, br, zstd
Content-type: application/json; charset=UTF-8
Content-Length: 27
Origin: https://front-end-client.netlify.app
DNT: 1
Sec-GPC: 1
Connection: keep-alive
Sec-Fetch-Dest: empty
Sec-Fetch-Mode: cors
Sec-Fetch-Site: cross-site
Priority: u=0
Pragma: no-cache
Cache-Control: no-cache

I have really no idea, because I tried everything I've read about and I'm so tired of this. I tried it out on 3 different browsers, turning off 3rd-cookies block...same result.

@Edit

I've found out that browser actually stores a cookie, but as a cookie of server domain! So e.x. client receives:

set-cookie: session-cookie=s%3AM-rccgHt_RGQyWfbIGrE_qyoWl_Sb1BU.zwMbyHDogXN31prfcisOOF%2BDuVBjAOZJ11uqLsiNqAo; Domain=front-end-client.netlify.app; Path=/; Secure; SameSite=None

but browser creates that cookie for back-end-client.onrender.com It's crazy!

Upvotes: 1

Views: 15

Answers (0)

Related Questions