How can you use cookies with superagent?

Kuryaki picture Kuryaki · Aug 12, 2012 · Viewed 31.4k times · Source

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?

Answer

Gaurav picture Gaurav · Oct 4, 2012

Use superagent.agent() (instead of plain old superagent) to make requests have persistent cookies. See 'Preserving cookies' in the superagent docs, or the code examples: agency.js, controller.test.js.