Is Axios failing to generate a cookie despite the presence of a set-cookie header?

Front-End: [Axios]

  const submitForm = async (e) => {
    e.preventDefault()
    const formData = new FormData(e.target)
    const email = formData.get('email')
    const password = formData.get('password')
    try {
      const response = await axios.post('http://172.16.2.19:3001/api/v1/auth/login', {
        email,
        password,
      })
      console.log(response.data) // I can successfully log in if email & password are correct.
    } catch (error) {
      console.log(error)
    }
  }

Back-End [Nodejs ExpressJs]:

Inside App.js:

const cors = require('cors')
app.use(cors({ credentials: true }))

Inside Login.js (/auth/login endpoint):

// ... code, then... if email & password are correct:
// 3600000ms = 1hour
res.cookie('jwt', token, { httpOnly: true, expires: new Date(Date.now() + 3600000 })
res.status(200).json({
    status: 'success'
    token,
    data: userDoc,
})

When I log in on my browser:

https://i.sstatic.net/MxFzr.png

I can successfully log in, but no cookies are being created, look here:

https://i.sstatic.net/1sdTv.jpg

  • The front-end HTTP service (React app) is hosted at http://172.16.2.19:3000
  • The back-end HTTP service (Express.js) is hosted at http://172.16.2.19:3001
  • The Axios requests from the front-end are sent to: http://172.16.2.19:3001

What seems to be the issue?

The absence of cookies being created in the browser is hindering my progress in developing the front-end application. To access any data from the API, I need to be authenticated as all the API routes are protected. Hence, I must send my JWT token with each request to the API.

edit **:

Here's the response from the /auth/login endpoint upon successful login:

https://i.sstatic.net/Ag6nu.png

  • I am using Brave Browser, the latest version.
  • I tested this on Firefox and encountered the same issue.

https://i.sstatic.net/aVrDD.jpg

Answer №1

If you're facing a similar issue, here's a quick solution:

To resolve the problem, simply modify your backend code as follows:

Update your backend code from:

const cors = require('cors')
app.use(cors({ credentials: true }))

to:

app.use(cors({ credentials: true, origin: true }))

Additionally, ensure that you're using withCredentials: true in the front-end for every request (especially for the login POST method and any other authenticated requests).

Why make this change?

By setting the origin property to true, you allow the request origin to be reflected. If needed, you can specify a particular domain as a string (e.g., http://localhost:3000), but setting it to true is a good choice when dealing with multiple clients.

It's important to note that the CORS issue only affects browsers and not other clients like mobile devices when specifying a domain for the origin field.

Answer №2

If you encounter a similar problem where your client and server are on separate domains, remember to configure the cookies with sameSite: 'none' and secure: true

https://web.dev/samesite-cookies-explained/

Answer №3

To verify, I recommend passing {withCredentials: true} as the third parameter in the axios function. This will enable the browser to include the cookie in the request.

Answer №4

In my opinion, it's not advisable to utilize the backend for storing cookies since cookies are distinct browser components unrelated to the database. However, I could be mistaken. Upon successful posting, the 'res' will yield a token which should be saved in the local storage of the browser.

const formSubmit = async (e) => {
e.preventDefault()
const formData = new FormData(e.target)
const email = formData.get('email')
const password = formData.get('password')
try {
  const res = await axios.post('http://172.16.2.19:3001/api/v1/auth/login', {
    email,
    password,
  })
  //saving tokens in browser's local storage
  
  localStorage.setItem('access_token',res.data.access);
  localStorage.setItem('refresh_token',res.data.refresh);
  console.log(res.data) // Successful login if email & password are accurate.
}

Subsequently, an authorization header needs to be created as shown below

headers:{
        Authorization: localStorage.getItem('access_token') 
            ? 'JWT '+localStorage.getItem('access_token')
            : null

    }

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

Show a checkbox element with a square in the center instead of a tick mark

Is there a way to create a custom checkbox in HTML with a black box in the center, similar to the third checkbox shown in the image below? I've noticed this design in many interfaces, but I haven't been able to find a satisfactory example online ...

Next.js - Anticipated that the server HTML would include a corresponding <div> within <div> tag

For a live demonstration, please click here In my current project, I am experimenting with creating a simple layout that adjusts based on the user's screen size. Specifically, on mobile devices, only the latest posts should be displayed. On desktops, ...

Storing an array of JSON objects in separate rows within an SQL database table

I need help with inserting data from an API post request into a MySQL table using Express JS. The JSON array contains multiple objects that I want to fill out the rows in the table, but I can't seem to get it right. Any assistance would be appreciated ...

Generating a JavaScript object from a string to optimize its compatibility with datatables

This inquiry pertains to the plugin available at: var hidecols = '{"sClass": "Hide", "aTargets": [0]},{"sClass": "asdf", "aTargets": [1]},{"sClass": "qwer", "aTargets": [2]}'; var hidecolsobj = eval('(' + hidecols + ')'); ...

Having trouble with @here/maps-api-for-javascript in Next.js - it's not functioning

Can anyone help me understand why @here/maps-api-for-javascript is not functioning properly in my Next.js application and producing the following error message: import H from "@here/maps-api-for-javascript"; export default H; ^^^^^^ SyntaxErr ...

What are the best practices for implementing media queries in Next.js 13.4?

My media queries are not working in my next.js project. Here is what I have tried so far: I added my queries in "styles.module.css" and "global.css" and imported them in layout.js I included the viewport meta tag under a Head tag in layout.js This is how ...

The functionality of the MVC jQuery grid is currently malfunctioning

Recently, I attempted to integrate a jQuery grid plugin from gijgo.com into my MVC application. Following the instructions provided on c-sharpcorner and/or codeproject meticulously, however, upon running the application, I encountered a troubling JavaScrip ...

Anticipating the completion of multiple observable subscription functions

Is there a way to replace and convert all words in an array using an object's method that returns an observable? I found a helpful solution on this post which uses bind to pass the correct value. After all subscriptions are complete, I want to execut ...

Limit file selection to images using MUI File Input

I am currently using MUI File Input in React for a file input element. The code I have works well, but I would like to restrict this file input to only accept images. How can I achieve this? Here is what I have done so far: const [locationImg, setLoc ...

Sign up for a new magazine or newsletter once your current one has been fully processed | React-Meteor

Currently, I am working with two publications: teams.dashboard and boards.board. My goal is to load the boards.board publication using the boardId from the first loaded Board, which can be accessed like this: Boards.find().fetch()[0]._id. I'm searchi ...

What is the best approach to managing a Symfony form that contains TWO CollectionType child forms?

I have been referring to the Symfony guide here which explains how to generate and save a collection of associated entities within a form. Following the example provided in the guide, I have successfully implemented the functionality for adding and removi ...

Utilizing static folders alongside routing in Express

I've encountered a significant challenge with Routing in Express. Within my project, there exists a directory called /public. Inside the /public folder are sub-folders such as: - public |- user |- common Initially, I was serving pages fr ...

Adjust the fixed navbar position in MaterializeCSS as you scroll

First of all, I apologize for my limited proficiency in English. I have a website with a company logo at the top and a navigation bar below it. My goal is to change the position of the navigation bar to the top when scrolling past the company logo. I att ...

typescript error caused by NaN

Apologies for the repetitive question, but I am really struggling to find a solution. I am facing an issue with this calculation. The parameters a to g represent the values of my input from the HTML. I need to use these values to calculate a sum. When I tr ...

Is there a way to retrieve the hand-drawn lines at no cost in the form of a list, with each line represented as a collection of coordinates

I am currently contemplating the idea of utilizing fabric.js for an online handwriting recognition system. In order to make this system work, I need to transmit the sketched lines as a collection of lines, where each line consists of several points. If a ...

Convert time display to a 24-hour format using JavaScript

I managed to convert the time format from GMT to my browser's local time using the following JavaScript code: var newDate = new Date(timeFromat); timeFormat = newDate.toLocaleString(); Now, I want to change the time format to a 24-hour clock format ...

Could there be a potential compatibility issue on my end with the mongoose 7.0.4 reference system?

Struggling with completing Dave Grey's MERN stack code tutorial, I encountered the following issue: My POST request seems to be stuck on the "Note.create" line without any response. The try-catch block doesn't throw any errors. //POST Method con ...

Incorporate variable key-value pairs into a JavaScript array or object

Is it possible to add a key value pair to an existing JavaScript associative array using a variable as the key? I need this for JSON encoding and prefer a simple solution over using plugins or frameworks. ary.push({name: val}); In the above code snippet, ...

How many documents are stored in MongoDB in total?

Seeking assistance with mongodb, as I am a newcomer to it and trying to determine the total number of records in a collection while utilizing node express. Here is my code snippet: let mongoose = require('mongoose'); let Patient = require(&apos ...

Utilizing Google Chrome Extension: Sharing variables between injected scripts via chrome.tabs.executeScript to another script injected in a similar manner

Can anyone help me with a coding challenge? I have two scripts injected in my popup.js and I need to make a variable defined in one script accessible to the other. Here's how I'm injecting the scripts: let sortFunction = function (goSortParam) { ...