0
0
Expressframework~30 mins

Why authentication matters in Express - See It in Action

Choose your learning style9 modes available
Why authentication matters
📖 Scenario: You are building a simple Express server for a small online store. You want to protect a special route that shows sensitive user information. To do this, you will add a basic authentication check.
🎯 Goal: Build an Express server with a protected route /profile that only allows access if a correct password is provided in the request headers.
📋 What You'll Learn
Create an Express app variable called app
Set a password variable called correctPassword with the value secret123
Add a middleware function called checkAuth that checks if the request header password matches correctPassword
Use the checkAuth middleware on the /profile route to protect it
💡 Why This Matters
🌍 Real World
Authentication is essential to protect user data and private routes in web applications. This project shows a simple way to check credentials before allowing access.
💼 Career
Understanding middleware and authentication in Express is a key skill for backend web development jobs.
Progress0 / 4 steps
1
Set up Express app
Create a variable called express by requiring the 'express' module. Then create a variable called app by calling express().
Express
Need a hint?

Use require('express') to import Express and then call it to create the app.

2
Add password variable
Create a variable called correctPassword and set it to the string 'secret123'.
Express
Need a hint?

Just create a simple string variable with the password.

3
Create authentication middleware
Write a middleware function called checkAuth that takes req, res, and next as parameters. Inside it, check if req.headers.password equals correctPassword. If yes, call next(). Otherwise, respond with status 401 and message 'Unauthorized'.
Express
Need a hint?

Middleware functions have three parameters and must call next() to continue.

4
Protect the /profile route
Add a GET route /profile to app that uses the checkAuth middleware. The route handler should send the text 'User profile data'.
Express
Need a hint?

Use app.get with the middleware as the second argument, then the handler.