Bird
Raised Fist0
Expressframework~10 mins

Protecting routes with auth middleware in Express - Interactive Code Practice

Choose your learning style10 modes available

Start learning this pattern below

Jump into concepts and practice - no test required

or
Recommended
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to import the Express module.

Express
const express = require([1]);
Drag options to blanks, or click blank then click option'
A"express"
B"http"
C"fs"
D"path"
Attempts:
3 left
💡 Hint
Common Mistakes
Using a wrong module name like "http" or "fs".
Forgetting the quotes around the module name.
2fill in blank
medium

Complete the code to create an Express app instance.

Express
const app = [1]();
Drag options to blanks, or click blank then click option'
Arouter
Brequire
Cexpress
Dmiddleware
Attempts:
3 left
💡 Hint
Common Mistakes
Trying to call require() instead of express().
Using undefined variables like router().
3fill in blank
hard

Fix the error in the middleware function to correctly call next.

Express
function authMiddleware(req, res, next) {
  if (req.user) {
    [1]();
  } else {
    res.status(401).send('Unauthorized');
  }
}
Drag options to blanks, or click blank then click option'
Ares.next
Breq.next
Cnext
Dnext()
Attempts:
3 left
💡 Hint
Common Mistakes
Writing next without parentheses.
Trying to call res.next() which does not exist.
4fill in blank
hard

Fill both blanks to protect the route with the auth middleware.

Express
app.[1]('/dashboard', [2], (req, res) => {
  res.send('Welcome to your dashboard');
});
Drag options to blanks, or click blank then click option'
Aget
Bpost
CauthMiddleware
Dexpress.json()
Attempts:
3 left
💡 Hint
Common Mistakes
Using POST instead of GET for a page route.
Using unrelated middleware like express.json() instead of auth middleware.
5fill in blank
hard

Fill all three blanks to create and use auth middleware that checks for a token header.

Express
function [1](req, res, next) {
  const token = req.headers['[2]'];
  if (token === 'secret') {
    next();
  } else {
    res.status(403).send('Forbidden');
  }
}

app.[3]('/protected', [1], (req, res) => {
  res.send('Protected content');
});
Drag options to blanks, or click blank then click option'
AauthMiddleware
Bauthorization
Cget
Dx-access-token
Attempts:
3 left
💡 Hint
Common Mistakes
Using wrong header names like 'authorization' when the code expects 'x-access-token'.
Using POST instead of GET for a simple protected page.

Practice

(1/5)
1. What is the main purpose of auth middleware in an Express app?
easy
A. To check if a user is allowed to access a route
B. To format the response data before sending
C. To log every request made to the server
D. To serve static files like images and CSS

Solution

  1. Step 1: Understand middleware role

    Middleware runs before route handlers to process requests.
  2. Step 2: Identify auth middleware function

    Auth middleware specifically checks user permissions to allow or deny access.
  3. Final Answer:

    To check if a user is allowed to access a route -> Option A
  4. Quick Check:

    Auth middleware = Access control [OK]
Hint: Auth middleware controls access to routes [OK]
Common Mistakes:
  • Confusing auth middleware with logging middleware
  • Thinking middleware serves static files
  • Assuming middleware formats response data
2. Which of the following is the correct way to use auth middleware for a route in Express?
easy
A. app.get('/profile', authMiddleware, (req, res) => { res.send('Profile'); });
B. app.get(authMiddleware, '/profile', (req, res) => { res.send('Profile'); });
C. app.get('/profile', (req, res) => { authMiddleware(); res.send('Profile'); });
D. app.get('/profile', (req, res) => { res.send('Profile'); }, authMiddleware);

Solution

  1. Step 1: Recall Express route syntax

    Middleware functions come before the final route handler in the argument list.
  2. Step 2: Check each option's order

    Only app.get('/profile', authMiddleware, (req, res) => { res.send('Profile'); }); places authMiddleware correctly before the handler function.
  3. Final Answer:

    app.get('/profile', authMiddleware, (req, res) => { res.send('Profile'); }); -> Option A
  4. Quick Check:

    Middleware before handler = app.get('/profile', authMiddleware, (req, res) => { res.send('Profile'); }); [OK]
Hint: Middleware goes before the route handler function [OK]
Common Mistakes:
  • Placing middleware after the handler
  • Passing middleware as the first argument instead of path
  • Calling middleware inside the handler instead of passing it
3. Given this auth middleware, what will happen when a request without a valid token hits the protected route?
function authMiddleware(req, res, next) {
  if (req.headers.authorization === 'valid-token') {
    next();
  } else {
    res.status(401).send('Unauthorized');
  }
}

app.get('/dashboard', authMiddleware, (req, res) => {
  res.send('Welcome to dashboard');
});
medium
A. The user sees 'Welcome to dashboard' regardless of token
B. The server crashes due to missing next() call
C. The user gets a 401 Unauthorized response if token is missing or invalid
D. The user gets a 404 Not Found error

Solution

  1. Step 1: Analyze authMiddleware logic

    If the authorization header equals 'valid-token', next() is called to continue.
  2. Step 2: Check behavior when token is missing or invalid

    Else block sends 401 Unauthorized response and does not call next(), blocking access.
  3. Final Answer:

    The user gets a 401 Unauthorized response if token is missing or invalid -> Option C
  4. Quick Check:

    Invalid token = 401 Unauthorized [OK]
Hint: Middleware sends 401 if token invalid, else calls next() [OK]
Common Mistakes:
  • Assuming next() is always called
  • Thinking user always sees dashboard
  • Confusing 401 with 404 errors
4. Identify the error in this auth middleware code:
function authMiddleware(req, res, next) {
  if (!req.user) {
    res.status(403).send('Forbidden');
  }
  next();
}
medium
A. Missing call to next() inside the if block
B. next() is called even after sending a response, causing an error
C. Status code 403 is incorrect for unauthorized access
D. req.user should be checked with req.auth instead

Solution

  1. Step 1: Understand middleware flow

    If !req.user is true, response is sent with status 403.
  2. Step 2: Check what happens after sending response

    next() is called unconditionally after the if block, so it runs even after response sent, causing errors.
  3. Final Answer:

    next() is called even after sending a response, causing an error -> Option B
  4. Quick Check:

    Call next() only if no response sent [OK]
Hint: Do not call next() after sending a response [OK]
Common Mistakes:
  • Calling next() after res.send()
  • Not stopping middleware after response
  • Using wrong status codes for auth errors
5. You want to protect multiple routes with the same auth middleware and also log the user ID if authenticated. Which is the best way to do this?
function authMiddleware(req, res, next) {
  if (!req.headers.authorization) {
    return res.status(401).send('Unauthorized');
  }
  req.userId = req.headers.authorization;
  next();
}

// How to apply this middleware and log userId for routes '/profile' and '/settings'?
hard
A. Apply authMiddleware after route handlers to log userId
B. Add authMiddleware only to '/profile' route and log userId in '/settings' without middleware
C. Call authMiddleware inside each route handler manually before logging userId
D. Use app.use(authMiddleware) before defining both routes, then log req.userId inside each route handler

Solution

  1. Step 1: Understand middleware application

    app.use(authMiddleware) applies middleware to all routes defined after it, protecting multiple routes easily.
  2. Step 2: Logging userId in route handlers

    Since authMiddleware sets req.userId, route handlers can access and log it safely after middleware runs.
  3. Final Answer:

    Use app.use(authMiddleware) before defining both routes, then log req.userId inside each route handler -> Option D
  4. Quick Check:

    Use app.use for shared middleware [OK]
Hint: Use app.use(authMiddleware) to protect many routes [OK]
Common Mistakes:
  • Applying middleware only to some routes inconsistently
  • Calling middleware inside handlers manually
  • Applying middleware after route handlers