39. Attaching the token to a request

So now we've created our token. We now need to pass it to the user so they can send it back on future requests to authenticate themselves on protected routes.

Attaching header

The canonical way of passing a JSON web token is to add it as an HTTP header, which is basically meta data that you can attach to a request. You could also add the token to the body or attach it as a cookie, but we'll be using the header.

We're going to add the token to the login endpoint, when we make it, but we also want to add it to the registration endpoint, here.

To add the header, let's chain an additional method in our response call which will be header. Headers have a key and a value, and these correspond to the two arguments you need for this method.

So our first argument will be a string "authorization", and the second will be a string "Bearer" followed by the token, so we'll just put a random token in for now.

server/controllers/user.js

const doc = await user.save();
res
  .header("authorization", "Bearer abc123")
  .send({ user: doc });

You may be wondering why we choose to name the header "authorization" specifically, and why we prefix the token with "Bearer". These are actually legacy things from the early HTTP spec. You don't need to do it like this, but it's best that you do because, as you'll see when we work on the frontend, authentication libraries will usually expect the token in this format.

Adding the token.

So now we need to get the real token and add it to the header. To do this, we'll create a new variable token underneath the doc we created when we created our new user.

We'll assign this the value that gets returned from the new instance method we just made, generateAuthToken.

We can then turn our header value into a template literal, and insert the token as a variable.

const doc = await user.save();
const token = await doc.generateAuthToken();
res
  .header("authorization", `Bearer ${token}`)
  .send({ user: doc });

Postman

Let's go over to Postman now, re-run the POST /users request, and if we look in the response body, then click the Headers section, we'll see that we now have an authorization header with a JSON web token!

Discussion

0 comments