0

I am trying to set/get cookies for users that browse on my web server, I found the following StackOverflow question: Get and Set a Single Cookie with Node.js HTTP Server and I was able to get the cookie set on the browser just fine. When I go to the cookie viewer I see the cookie I set just as I want it. The problem comes when I try to view the cookies, the request.headers.cookie is always undefined. How would I go about getting the cookies on a users browser, preferably without NPM modules and purely node and its own modules?

How I'm setting the cookie (this works fine, I am able to see this cookie in the browser when I go to view my cookies):

response.writeHead(statusCode, {
  'Set-Cookie': cookie
})
// statusCode = 200
// cookie = 'token=SOME_TOKEN'
// In the browser I see the exact cookie I set

How I'm trying to get the cookie (not working always undefined):

let cookies = request.headers.cookie
// This returns undefined always
// even when I can view the cookie in the
// browser the request is coming from

// Also quick note: I'm currently not
// parsing the cookies out to view them as
// a JSON object because I can not get any
// of the cookies

EDIT: It seems I have finally found the error, it sets the cookie path to be whatever path I set the cookie on, so I was setting the cookie on the "/auth" route. How can I make it so that this cookie is accessible from any route the user goes to?

Garret
  • 144
  • 12
  • Also if it helps: I'm using the Firefox browser on ubuntu when making the browser requests and seeing the cookies. – Garret May 12 '19 at 03:28

1 Answers1

2

Ok I finally found the solution, my error was that it was auto-setting the path of the cookie to be "/auth" so I could only access the cookie if the url requested contained "/auth", where I set the cookie I changed it to the following:

response.writeHead(statusCode, {
  'Set-Cookie': cookie + '; Path=/'
})

And now I can access my cookie

Garret
  • 144
  • 12