0
0
Expressframework~30 mins

JWT token creation in Express - Mini Project: Build & Apply

Choose your learning style9 modes available
JWT Token Creation with Express
📖 Scenario: You are building a simple Express server that creates JSON Web Tokens (JWT) for users after they log in. JWTs help keep users logged in securely.
🎯 Goal: Build an Express server that creates a JWT token using a secret key and user data.
📋 What You'll Learn
Create an Express app variable called app
Create a secret key variable called jwtSecret with value 'mysecretkey'
Use the jsonwebtoken library to create a token with user info
Create a POST route /login that returns a JWT token
💡 Why This Matters
🌍 Real World
JWT tokens are widely used in web apps to securely keep users logged in without storing passwords on the client.
💼 Career
Understanding JWT creation is essential for backend developers working on authentication and security in web applications.
Progress0 / 4 steps
1
Setup Express app and user data
Create an Express app variable called app by requiring express and calling it. Also create a user object called user with id 1 and username 'alice'.
Express
Need a hint?

Use const app = express() to create the app. Define user as an object with id and username.

2
Add JWT secret key
Create a constant called jwtSecret and set it to the string 'mysecretkey'.
Express
Need a hint?

Just create a constant string variable named jwtSecret.

3
Create JWT token in /login route
Require the jsonwebtoken library as jwt. Then create a POST route /login on app. Inside the route, create a token by calling jwt.sign() with the user object and jwtSecret. Send the token as JSON with key token.
Express
Need a hint?

Use jwt.sign(user, jwtSecret) to create the token. Send it back with res.json({ token }).

4
Start the Express server
Add code to start the Express server by calling app.listen() on port 3000. Inside the listen callback, log the message 'Server running on port 3000'.
Express
Need a hint?

Use app.listen(3000, () => { console.log('Server running on port 3000') }) to start the server.