Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Express doesn't set a cookie

I have problem with setting a cookies via express. I'm using Este.js dev stack and I try to set a cookie in API auth /login route. Here is the code that I use in /api/v1/auth/login route

res.cookie('token', jwt.token, {expires: new Date(Date.now() + 9999999)}); res.status(200).send({user, token: jwt.token}); 

In src/server/main.js I have registered cookie-parser as first middleware

app.use(cookieParser()); 

The response header for /api/v1/auth/login route contains

Set-Cookie:token=eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiJ9.eyJ..  

but the cookie isn't saved in browser (document.cookie is empty, also Resources - Cookies tab in develepoers tools is empty) :(

EDIT: I'm found that when I call this in /api/v1/auth/login (without call res.send or res.json)

res.cookie('token', jwt.token, {expires: new Date(Date.now() + 9999999), httpOnly: false}); next();

then the cookie is set AND response header has set X-Powered-By:Este.js ... this sets esteMiddleware in expres frontend rendering part.

When I use res.send

res.cookie('token', jwt.token, {expires: new Date(Date.now() + 9999999), httpOnly: false}).send({user, token: jwt.token});` next(); 

then I get error Can't set headers after they are sent. because send method is used, so frontend render throw this error.

But I have to send a data from API, so how I can deal with this?

like image 476
Mira Avatar asked Apr 24 '16 14:04

Mira


People also ask

How do you set an express session cookie?

var cookieSession = require('cookie-session') var express = require('express') var app = express() app. use(cookieSession({ name: 'session', keys: ['key1', 'key2'] })) // Update a value in the cookie so that the set-cookie will be sent. // Only changes every minute so that it's not sent with every request. app.

How does res cookie work?

The res. cookie() function is used to set the cookie name to value. The value parameter may be a string or object converted to JSON. Parameters: The name parameter holds the name of the cookie and the value parameter is the value assigned to the cookie name.

What is the difference between Express session and cookie session?

Cookie session is basically used for lightweight session applications where the session data is stored in a cookie but within the client [browser], whereas, Express Session stores just a mere session identifier within a cookie in the client end, whilst storing the session data entirely on the server.


2 Answers

I had the same issue. The server response comes with cookie set:

Set-Cookie:my_cookie=HelloWorld; Path=/; Expires=Wed, 15 Mar 2017 15:59:59 GMT  

But the cookie was not saved by a browser.

This is how I solved it.

I use fetch in a client-side code. If you do not specify credentials: 'include' in fetch options, cookies are neither sent to server nor saved by a browser, although the server response sets cookies.

Example:

var headers = new Headers(); headers.append('Content-Type', 'application/json'); headers.append('Accept', 'application/json');  return fetch('/your/server_endpoint', {     method: 'POST',     mode: 'same-origin',     redirect: 'follow',     credentials: 'include', // Don't forget to specify this if you need cookies     headers: headers,     body: JSON.stringify({         first_name: 'John',         last_name: 'Doe'     }) }) 
like image 137
Green Avatar answered Sep 22 '22 00:09

Green


Struggling with this for a 3h, and finally realized, with axios, I should set withCredentials to true, even though I am only receiving cookies.

axios.defaults.withCredentials = true;

like image 35
DedaDev Avatar answered Sep 21 '22 00:09

DedaDev