This week we have been tasked with building a REST API that returns JSON data for our group projects, and my group made one that contains data about books that our cohort has read.
We added user authentication for our POST routes so only logged in users can add resources to the database. We did this with token-based authentication using the jsonwebtoken
Node.js npm package.
When a new user signs up to our API they get a JWT that is signed with a secret that we stored as an environment variable in our .env
file.
const dotenv = require("dotenv"); const jwt = require("jsonwebtoken"); const secret = process.env.JWT_SECRET; dotenv.config(); function signUp(req, res) { // run database query function that creates a new user .then((user) => { const access_token = jwt.sign({ user: user.id }, secret, { expiresIn: "1h" }); user.access_token = access_token; // send user object } // error-handling };
When the user signs in successfully by making a POST request to the API, we send the access_token
property of their user object in the response body. The user can then send this JWT in the authorization headers when making a request to our API that requires authorization.
This was all working great on our local servers, but we were unable to sign up or sign in to our API once deployed on Heroku. We were scratching our heads until it dawned on me as I was biting into my sandwich at lunch: we needed to add our JWT_SECRET
variable to our Config Vars on Heroku. Problem solved 🥳!