Skip to main content

How to set up your client

Remember to set up your session middleware

Even though this is the "How to set up your client section", it is good to start with our recommended configuration for your server in case you are using express-session (if you don't know what we are talking about, go to our Step-by-step Guide), which is the following:

app.use(session({
secret: '<YOUR SESSION SECRET>',
resave: true,
saveUninitialized: false,
cookie: {
secure: false, // if true only transmit cookie over https
httpOnly: false, // if true prevent client side JS from reading the cookie
maxAge: 1000 * 60 * 10, // session max age in millisecond
},
sameSite: 'lax' // or 'strict' if your client and server have the same origin url
}));

Set the credentials attribute in your requests

Once your client has logged in, in order for each request to be authenticated, you need to set the credentials (or withCredentials if you are using axios, or its equivalent in whatever requests module you are using) attribute to true in each of your requests.

Fetch API

If you are using javascript's native fetch api, remember to set the credentials attribute to true each time you make a request:

Example

fetch('https://URLToServer.example/protectedRoute', {
// SET THE credentials ATTRIBUTE TO true
credentials: true,

body: JSON.stringify({
someProperty: 'A normal request body... Nothing to see here...'
}),
headers: {
// ...
}
})

Axios

When using axios, make sure to set the withCredentials attribute to true, like this:

import axios from 'axios';

axios.post('http://URLToServer.example/protectedRoute', yourRequestBody, {
withCredentials: true
});

// Or if using GET...
axios.get('http://URLToServer.example/protectedRoute', {
withCredentials: true
})
tip

Just so that you don't have to write withCredentials: true in all of your requests, we recommend you create an axios instance like this:

credentialsAxios.js
const credentialsAxios = axios.create({
withCredentials: true
});

export default credentialsAxios;

And use it whenever you want to make a request to the server:

import credentialsAxios from './credentialsAxios.js';

credentialsAxios.post('http://URLToServer.example/protectedRoute', yourRequestBody, {/* ... */});