Using session cookies with Node.js and Axios
axios is a popular HTTP client for Node or the browser. It has a very simple and intuitive interface, and is therefore my favourite HTTP client to use in frontend development.
However, whilst the browser usually takes care of cookies and sessions during frontend development, you have to keep track of these yourself when using axios in node.js. This is a pain if for some reason the API you are interacting with makes use of sessions.
Here is a very simple code sample to illustrate the problem:
import axios from 'axios';
await axios.post('https://example.com/login', {
name: 'me',
password: 'p@ssw0rd',
});
const data = await axios.get('https://example.com/data');
That second call to https://example.com/data will not use the cookies from the first call, and therefore will start a new session, and be seen as unauthenticated by the server.
Thankfully the axios-cookiejar-support package adds support for tough-cookie to axios, which makes handling of session cookies with axios in Node.js very simple:
Using axios-cookiejar-support to add support for Session Cookies to Axios.
Firstly, you need to install your requirements:
npm install tough-cookie axios-cookiejar-support
Secondly, import both CookieJar and the axios-cookiejar-support wrapper:
import { CookieJar } from 'tough-cookie';
import { wrapper } from 'axios-cookiejar-support';
Thirdly, create a cookie jar and configure an axios client instance to make use of it:
const jar = new CookieJar();
const client = wrapper(axios.create({ jar }));
And finally, simply use this client wherever you would’ve previously used axios. The full sample script from above would then look as follows:
import axios from 'axios';
import { CookieJar } from 'tough-cookie';
import { wrapper } from 'axios-cookiejar-support';
const jar = new CookieJar();
const client = wrapper(axios.create({ jar }));
await client.post('https://example.com/login', {
name: 'me',
password: 'p@ssw0rd',
});
const data = await client.get('https://example.com/data');
Your client now automatically keeps track of session cookies for you across subsequent requests.