How to make authenticated requests on Supertest

Let's see how to make authenticated requests on Supertest, so if you need to add an Authorization header or send requests after a login or with a cookie, keep reading!

Add a Authorization header ๐Ÿ”‘

Simple example to add the Authorization header in a Supertest request:

supertest('http://localhost:8080')  
  .get(โ€˜/api/resourceโ€™)
  .set('Authorization', 'Bearer ' + token) 
  .end((err, res) => {  
     if (err) {
       return done(err);
     }
  });

Note this example add it using .set('Authorization', 'Bearer ' + token)

After login or using a cookie ๐Ÿช

For example, if you are testing an endpoint which requires be logged in and need to test the login too, let's see one way to test it

First, test the login and save your-cookie to use it later:

let session = null;
supertest('http://localhost:8080')  
  .post(โ€˜/loginโ€™)  
  .send(loginJson)  
  .end((err, res) => {  
     if (err) {
       return done(err);
     }
     session = res.header['your-cookie'];  
     done();  
 });

Then use your session cookie in the next requests:

supertest('http://localhost:8080') 
  .delete(`/api/resource/${ resourceId }`)
  .set('Cookie', session)
  .end((err, res) => {
    if (err) {
      return done(err);
    }
    done();  
  }); 

These are super simple examples just to point the use of set() for auth in Supertest

Leave a comment with your questions or doubts, happy to help you ๐Ÿ™‚
Thanks for reading! ๐Ÿ‘‹

David Burgos

Read more posts by this author.