How can you use cookies with superagent?

Viewed 37345

I'm doing cookie session management with express with something like this:

req.session.authentication = auth;

And I verify the authenticated urls with something like

if(!req.session.authentication){res.send(401);}

Now I'm building tests for the URLs with mocha, superagent and should, however I can't seem to find a way to get/set the cookie with superagent. I even tried to request the login before the authenticated test but it is not working,

I have tried adding the request to the login in the before statement for the mocha BDD suite, however it is still telling me that the request is unauthorized, I have tested the authentication doing the requests from the browser, however it is not working from the suite any ideas why?

6 Answers

If the issue is in sending cookies for CORS requests use .withCredentials() method described here

request
  .get('http://localhost:4001/')
  .withCredentials()
  .end(function(err, res) { })

2020 +

A clean way to do it is:

  • create a simple cookie store
  • abstract set Cookie to send it in each request
  • update the cookie only when needed

Note I keep the same URL because I use graphql but you can make it a parameter:

const graph = agent =>
  agent.post('/graph')
    .set('cookie', cookieStore.get());

const handleCookie = res =>
  cookieStore.set(res.headers['set-cookie'][0]);

let currentCookie="";
const cookieStore = {
  set: cookie=>{currentCookie=cookie},
  get: cookie=>currentCookie,
};

module.exports = {graph,connectTestUser,handleCookieResponse};

You can now just use graph(agent) to send a request and handleCookie(response) when you have a response that may update your cookie (set or clear), example:

graph(agent).end((err,res) => {
  if (err) return done(err);
  res.statusCode.should.equal(200);
  handleCookie(res);
  return done();
});

Add a cookie to agent cookiejar:

const request = require('superagent');
const {Cookie} = require('cookiejar')
const agent = request.agent()

agent.jar.setCookie(new Cookie("foo=bar"))

  
Related