React's JS is having trouble accepting cookies from the express server

I've encountered an issue where sending cookies from my express server using res.cookie() is not working with the front end. Even though I include {withCredentials:true} in the get requests, the cookies are not being set in the browser's application tab. Interestingly, when I try the requests with Postman, the middleware works perfectly and the cookies are shown. I have tried different browsers and devices, but the issue persists. Here is my CORS configuration:

app.use(
  cors({
    credentials: true,
    origin: [
      "http://localhost:3000", 
    ],
    methods: ["GET", "POST"],
  })
);

Cookie parser configuration:

app.use(cookieParser())

This is the GET request to check if the user is already logged in:

await axios
    .get("http://192.168.0.141:3001/login", { withCredentials: true })
    .then(async (response) => {
        if (response) {
            loggedIn = true
        }
    })
    .catch(async err => {
        loggedIn = false
    })

The JWT middleware:

const validateToken = (req, res, next) => {
    const accessToken = req.cookies["access-token"]
    if (!accessToken) { return res.status(400).json({ error: "user not authenticated" }) }
    try {
        const validToken = jwt.verify(accessToken, "test");
        if (validToken) {
            req.authenticated = true
            return next();
        }
    } catch (error) {
        return res.status(400).json({ error: error });
    }
}

If you require further clarification, please let me know. Thank you for your assistance.

Answer №1

Are you certain that no cookies have been set? How are you verifying this? Does the response include the Set-Cookie header? What specific cookie parameters are being utilized (e.g. secure, same-site)? It's important to remember that cookies in a browser are associated with the domain that initially set them. If you're inspecting through the Application tab of developer tools, make sure to open the developer tools on http://192.168.0.141:3001 instead of http://localhost:3000. While you may not visually see those cookies in your SPA's Application tab, the browser should still send them along with any XHR request, allowing you to view them within the request's Cookie header in the Network tab.

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

Cleaning up React async functions using hooks for fetching data

This code snippet is from a functional component. Within this component, there is a submit() function that handles form submission: async function handleSubmit(event) { event.preventDefault(); try { let resp = await fetch("FOOBAR/BAX", { ...

Choosing a default selection in a nested v-for loop for a select box

Currently, I have a list of items that users can add new items to. Each item is required to have a select box, and the selected value from the select box should be assigned as the item's value. In an attempt to bind the select box to the item using t ...

Mapping Longitude and Latitude with TopoJSON and D3

Currently utilizing the UK Geo JSON found at this link to generate a UK SVG Map. The goal is to plot longitude and latitude points onto this map. The GeometryCollection place is being added to the map in the following manner: data.objects.places = { ...

Optimal method for saving authenticated user in redux state

I am currently working on developing an application with the following technologies: Next.js An Express API Redux-Toolkit and RTK Query All of the authentication logic has been implemented successfully, but I have encountered a problem. After a successf ...

Converting long date format to short date format: yyyy-mm-dd

Is there a way to convert the long date format from "Sat Dec 13 2014 06:00:00 GMT+0600" to "2014-12-13" in yyyy-mm-dd format? <script> function myDate(val) { var now = new Date("<?php echo $Cnextdue;?>"); now.setDate(now.getDate() + 30*val); ...

Vertically animating an image using jQuery

I have been experimenting with trying to make an image appear as if it is floating by using jQuery to animate it vertically. After some research, I stumbled upon this thread: Animating a div up and down repeatedly which seems to have the solution I need. H ...

insert a new field into the database within Prisma while ensuring existing table data remains untouched

I have been working with the Prisma ORM and I currently have some data in my table. This is how my model looks: model User { id Int @default(autoincrement()) @id username String @db.VarChar(100) @unique } model Post { id Int @id @defa ...

Transforming Jquery into vanilla JavaScript and sending a POST request

Hey everyone, I'm in the process of converting Jquery code to pure javascript and encountering some difficulties with the following snippet: $.post('ajax_data',{action:'service_price',service:service,quantity:quantity,dripfeed:drip ...

Having difficulty in displaying database values in HTML modal using PHP

On my PHP page, I have a setup that displays data based on the fetched id from the URL. Everything is working smoothly, but when I click a button to show a modal with additional information, the modal appears blank. Here is the code snippet I am using: ...

Display all y-axis values in the tooltip using HighCharts

I utilized a chart example from http://www.highcharts.com/demo/column-stacked When you hover the mouse over a column, it displays the value of the y axis being hovered and the total value. I am interested in having the tooltip show the values of all 3 y ...

Struggling with slow response times when interacting with Firestore in Firebase Cloud Functions?

I am currently experiencing performance issues with a simple Cloud Function in Firebase. This function is responsible for taking JSON data through an HTTP POST request and storing it in a Firestore collection. Despite being assigned 512MB of memory, the pe ...

Toggle divs by using a checkbox (Vue.js)

On my authentication page, I have implemented a checkbox that I want to use to toggle between Sign Up and Sign In forms. When the checkbox is clicked, it should display the Sign Up form, and when it's unchecked, it should show the Sign In form. I fou ...

Ways to pause for the completion of multiple HTTP promises and display a modal exclusively when all promises result in failure

There are two separate HTTP calls on a page that need to be handled independently. vm.$onInit = function() { .... .... //Retrieve all items during initialization ds.getAllItems().then(function(result){ vm.items = result; },funct ...

Custom palette in Material UI design palette allows users to create

Hey there everyone! I've been working on a website using ReactJS and Material UI, starting with this cool template. One thing I'm trying to do is change the color of the TextField when it's focused. Right now it's blue, but I want it ...

Is it possible to showcase the data from three or more PHP files on a single webpage?

I currently have three PHP files: pie.php, bar.php, and line.php. When each file is run individually, it displays a webpage with a pie chart, bar chart, or line graph respectively. However, running all three files opens up separate webpages for each graph. ...

How do you populate a dropdownlistfor in ASP.NET MVC after a form

My issue is that <form> @Html.DropDownListFor(x => x.City, provinces, "--Select City--", new { @class = "dropdownList" }) @Html.DropDownListFor(x => x.district, Enumerable.Empty<SelectListItem>(), "--Select district--") < ...

Dealing with multiple distinct fields errors in MongoDB using Node.js

Suppose I have a unique constraint on two fields, username and email. When catching an error using try catch, the err.code distinguishes between a unique error and others, but how can we differentiate between a username unique error and an email unique err ...

Issues with JQuery scroll() / scrollTop() functionality in Internet Explorer and Firefox

Our current script showcases a dotted line starting from the top of the screen leading to an up arrow. The position of the arrow changes based on how far the user has scrolled down the page, allowing them to click on the arrow and scroll back to the top. W ...

Repetitive bouncing in a trampoline leads to the error message "Call stack has reached maximum size"

I have been delving into the world of blockchain and experimenting with a simple implementation of "proof of work". Proof of work: export function mineBlock(difficulty: number, block) { const prefix = Array(difficulty + 1).join("0"); function mine(b ...

A direct connection between NextJS and uwsgi is not possible

I am currently working on developing an application using django for the backend and nextjs for the frontend. The backend is being managed by uwsgi. uwsgi --http 0.0.0.0:3000 -w project.wsgi --master --harakiri=60 --pidfile=uwsgi.pid Whenever I try to run ...