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

AngularJS function orderBy reverses the array instead of sorting it

I encountered an issue where, after clicking the 'order button', the table does not order as expected. Instead, it reverses all the td elements. For example, 'A', 'C', 'B' becomes 'B', 'C', "A". I ...

What is the best way to obtain a user's ID on the server side?

I'm currently working on a node.js application using express and I am in need of retrieving the user ID. I would like to have something similar to "req.userID" so that I can use it in the following way: var counter=0; var user = new Array(); router.g ...

The NodeJS server experiences a crash immediately after attempting to save data into the MongoDB database

I have encountered an issue with a script that saves objects to a MongoDB database using mongoose. The object is successfully saved to the database, but immediately after, the server crashes and throws the error message: catch(err) { process.nextTick(funct ...

How can I transfer an image from the clipboard onto a fabric.js canvas?

I am currently working on developing a function that will allow users to paste an image from their clipboard onto a canvas as a new fabric.Image(). However, every search result I come across either discusses cloning existing objects within the canvas or pa ...

Improved Approach for Replacing if/else Statements

I'm looking to streamline the controller used in my SQL command for filtering records based on specific criteria. The current approach below is functional, but not without its limitations. One major issue is scalability - adding more criteria in the f ...

Tips for converting a number into a percentage with two decimal places using FormatJs Message Syntax

With the react-intl library, I am encountering a message that looks like this: serviceFee: { en: 'Service fee: ({fee, number, percent})', ... }, Upon calling <FormatMessage id="serviceFee" values={{ fee: 0.0625 }} /> I anticipate th ...

What is causing my animation to jump when using the Web Animation API reverse() function?

I've come across various sources stating that when you call reverse() while an animation is playing, it should have the same effect as setting playbackRate to -1. However, in my case, using reverse() makes my animation behave erratically and jump arou ...

Setting environment variables using the node command is successful on Linux and macOS platforms, however, it may not function properly

When I clone a project using git, I encounter issues running npm run build on Windows. The command works fine on Mac and Linux: "build": "API=https://dev-api.myexample.com/v1.0 babel-node build.js", An error message is displayed: 'API' is no ...

Retrieving information from GraphQL using express-graphql and a web server client

I am struggling with making an HTTP fetch request on a standard apollo graphql-server-express Despite following the advice on graphql.org, I have had no success. To test this, I have been using the Fusetools News Feed Example and replacing the fetch call ...

Tips on emphasizing all div elements and incorporating navigation to each of them

I am seeking a method to enhance a div with highlighting when there is a click or mouseover event. For instance, changing or adding a border color using JavaScript on click or mouseover is straightforward. Recently, I have been contemplating the idea of a ...

Cannot chain promises using 'then'

Having trouble understanding why the 'describeDir' promise chain is not working properly. Can anyone help me figure out what I did wrong here? Everything in the code seems to run, but functions like then or finally from the promise API never get ...

Uploading photos from iOS devices takes an eternity

I'm facing an issue with my React-Native iOS front-end not being able to upload images to my Node.JS (Express + Multer) back-end. While the Android version of my front-end works seamlessly without any problems, uploading images from an iOS device ten ...

How can I prevent an HTML element from losing focus?

Currently, I am developing an online editor that requires accurate character inputs. To achieve this, I have implemented the jQuery.onKeyPress event on a textarea element. This approach was chosen because obtaining character inputs from the body directly p ...

Steps for linking a keypress to trigger a specific action

I need help creating a script that will redirect to a URL when a button is clicked. Below is the code I have developed. HTML : <a id="#next" href="example.com">↵</a> <a id="#previous" href="example.com">↳</a> JS : $(document ...

Generate an HTML dropdown menu based on the item selected from the autocomplete input field

I have a PHP page that searches the database and returns JSON results to an autocomplete input field: When I display the response from the PHP file (as shown above), it looks like this: { "success": true, "results": [{ "name": "Bananas, r ...

Unusual shadow cast by the box's silhouette

I am currently facing an issue with a box and its shadow. When I close the box, a different shadow lingers behind. I have tried troubleshooting this problem but cannot pinpoint the source. I have included the relevant code files in the specified folders. I ...

How can I exclude GET /favicon.ico from the express.logger() for all requests in Node.js/Express.js?

I am looking to log all user requests except for those related to favicon.ico. Initially, I considered creating a function and then calling express.logger(). However, I discovered that this approach doesn't work when trying to call express.logger() fr ...

Unable to view Google Map markers within my XPath elements while using Selenium?

Looking to extract data from a Google Maps applet. The specific page can be found here: You can click on items on the map to view displayed information. While typical Google Maps show marker elements, I cannot see them on the provided link when inspecti ...

Tips on implementing live updates in Firebase without the need for reloading the page

After a user changes their profile picture, the update does not appear until they refresh the page. Here is the code snippet causing this issue: const handleProfile = async (e: any) => { const file = e.target.files[0] const storageRef = firebase ...

How to control Formik inputs from an external source

I'm currently developing an application with speech-to-text commands functionality. I have created a form, but I am looking to manipulate the input elements from outside the form framework. <form id="myform"> <input type="tex ...