What could be causing my CORS fetch request to not send cookies to the server?

Trying to work out a CORS request using the fetch method:

    fetch('https://foobar.com/auth', {
      method: 'GET',
      mode: 'cors',
      credentials: 'include',
    })

The server-side code in express for implementing CORS protection on one route is as follows:

app.get('/auth', cors({
    origin: [
        'http://localhost:8080',
        'http://127.0.0.1:8080'
    ],
    credentials: true,
    preflightContinue: true
}), (req, res) => {
    const { jwt } = req.cookies;
    console.log('JWT is: ', jwt);
    res.json({ jwt });
});


Unfortunately, even though the request includes a cookie, the response always comes back empty.

The response headers show:

access-control-allow-credentials: true
access-control-allow-origin: http://127.0.0.1:8080

Directly hitting the /auth route on the server does return JSON with the JWT token stored as a cookie that passes between client and server.

{"jwt":"[token string here]"}

In addition, the response headers also include:

set-cookie: connect.sid=s%3As-DAIzZjWT4C3xxxxxuAUgE; Path=/; HttpOnly; Secure

Questions arise about whether the set-cookie for the JWT should be visible in the response, indicating if it's being handled correctly by the server and sent back in the response to the CORS request. The process involves setting proper headers on the server side and specifying correct origins while enabling credentials to receive cookies.

Answer №1

The issue arose from express not properly generating the cookie. To resolve this, it is essential to include sameSite: 'none' as a parameter to allow CORS requests to utilize it.

const jwt = "abc123";
const expiresIn = 60 * 60 * 24 * 5 * 1000;
const options = { secure: true,  sameSite: 'none', httpOnly: true, maxAge: expiresIn };
res.cookie('jwt', jwt, options );

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

A guide to creating an HTTPS request using node.js

I am currently in the process of developing a web crawler. Previously, I utilized the following code for HTTP requests: var http=require('http'); var options={ host:'http://www.example.com', path:'/foo/example' }; ...

Quick question about utilizing Ajax with spans

<span name = "menu"> <!-- javascript here --> <!-- content loaded via ajax --> </span> <span name = "content"> <!-- content loaded via ajax --> <!-- updated by buttons from the menu--> </span> Seeking a ...

Incorporating the Crypto-js library into an Express application

I’ve encountered an issue while working on a user registration and login system where I am unable to encrypt the data successfully. Below is the Express code snippet: var express = require("express"); var router = express.Router(); var mysql = require ...

Unable to utilize material tabs in this situation

Discovering the material tabs feature at https://material.angular.io/components/tabs/api#MatTab got me excited to implement it in my project. After adding the suggested import, I encountered an issue where I couldn't find the module "@angular/materia ...

Troubleshooting Parse Server and Express: Dealing with ParseError causing site to crash and restart issues

I recently set up a Bitnami Parse stack on a Google Cloud VM. This setup consists of Apache functioning as a proxy, followed by a MEAN stack managing parse server and dashboard functionalities. Initially, everything seemed to be running smoothly as I coul ...

Absolute file path reference in Node.js

I'm working on a Node.js project using WebStorm IDE. Here's the structure of my project: The root folder is named "root" and inside are 2 folders: "main" and "typings". The "main" folder has a file called "foo.ts", while the "typings" folder co ...

When a VueJS button is located within a div that also contains a link, clicking on

Can someone help me with my HTML issue? <a href="/someplace"> <div> <vuecomp></vuecomp> <span>Click row for more info</span> </div> </a> Following is the Vue component I am working on... ...

What are the steps to resolve a Fetch request issue with a Node.js server?

I am attempting to make a simple POST request using the fetch method. I am working on building a contact form using Vanilla Javascript, HTML, and CSS on the front end, while utilizing Node.js / Express on the backend. Take a look at my front end code: ...

What is the reason for jQuery returning an integer instead of an object?

Currently, I am attempting to preselect an option within a <select> tag based on a variable. However, while using jQuery to select the elements and iterating through them with .each(), it appears to be returning integers instead of objects, making .v ...

Javascript Flickering Effect in HTML5

Currently, I am in the process of creating a simple game using javascript without jQuery. However, I am facing an issue with flickering on the canvas due to the clearing command. After researching solutions online, I came across suggestions for implementin ...

Configure Protractor's configuration file to utilize a personalized reporter

I'm in the process of setting up end-to-end tests using protractor.js, but I am not happy with how the default reporter displays results on my terminal window. Is there a way to customize the reporter configuration to make it easier to read and more ...

In search of an effortless method to effortlessly select numerous elements using a handy bookmarklet

My goal is to develop a bookmarklet that can perform various functions on different webpages with ease. The concept involves placing it in a convenient location, such as the bookmark bar, and executing a "standard function" on a particular page. Instead of ...

After triggering an action, I am eager to make a selection from the store

To accomplish my task, I must first select from the store and verify if there is no data available. If no data is found, I need to dispatch an action and then re-select from the store once again. Here is the code snippet that I am currently using: t ...

After submitting a multi-image form from Angular, the "req" variable is not defined

I'm currently facing an issue with submitting a form from Angular 7 to a Node backend using Multer as middleware and Express.json() as bodyParser. While the text data is successfully transmitted to the backend, the image fields are appearing empty {}. ...

Using the power of node.js to iterate through a loop of queries and execute

While I am running a for loop, within the loop itself I am executing a PostgreSQL query and storing the result in an array. However, I am unable to determine the order of execution. Here is my code: var array =[]; for(var i = 0 ; i< latitude.le ...

What is preventing module C from receiving the socket io event "hi"?

How can I call a different module for each socket path? Here is the updated server code: require('dotenv-flow').config(); const express = require('express'); const app = express(); const http =require('http'); const httpSer ...

"Missing the import of material-ui search icons is causing a functionality issue

import React from 'react' import {Search} from "@material-ui/icons/Search" const App = () => { return ( <div> <Search/> </div> ) } export default App The exported component 'Search' (impor ...

HtmlUnitDriver fails to execute javascript while loading a page from a URL

My issue revolves around testing my website page, where elements displayed with javascript are missing when viewed through the HtmlUnitDriver. I am currently using selenium-java version 3.141.59 and htmlunit-driver version 2.33.3. Below is a snippet of my ...

"Implementing constraints in Postgres using Node.js

Currently, I am struggling with writing a constraint code to handle situations where a user tries to search for an id that does not exist in the database (specifically PostgreSQL). Despite my efforts, the if statement in the code below does not seem to be ...

Leveraging Jquery to retrieve multiple values for dynamic updating in HTML

As I ponder over this dilemma, a suitable title eludes me to encapsulate my query. Behold the code in question: $(document).ready(function() { setInterval(function(){ $.get('/battleship/update_game/{{info.gameid}}/{{user.username}}', ...