Automatic JWT Token setup in Postman
Sadat Jubayer
January 19, 2023
• 2 min read
While working with APIs, we test them in an API client, and the most popular client is Postman. If the API has an authentication system, we log in through an endpoint and collect a JWT (JSON web token). Then we can access protected routes by setting the token into the header. We can automate this manual process by using Postman's environment variables. Before that, let's get an idea about Postman's environment variables.
Postman's Environment Variables
If our API's Base URL is localhost:3000
, instead of writing this in every request, we can set this in an environment variable and use it like this {{URL}}/endpoint
. Later, by changing the variable, we can simply test the production version of the application.
Set an Environment Variable
In Postman: go to Environments → Create new Environment → Enter a name, a variable name, and the value for your environment.
In this example, the environment is named Todo Project
with the variable name URL
set to localhost:3000
.
After saving, activate the environment by clicking on the check icon. Now, we can access any route like this - {{URL}}/route
.
Set Token Automatically
Let’s say we have an endpoint named {{URL}}/user/login
that returns a token if we send valid credentials. Another endpoint {{URL}}/todos
requires authentication using the token.
The plan is to take the token from the response and set it as an environment variable, so we don’t need to manually set it in every request that requires authentication.
In the {{URL}}/user/login
tab, go to the Tests tab and add these two lines of code: