0
0
NextJSframework~10 mins

Why middleware intercepts requests in NextJS - Test Your Understanding

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to create middleware that intercepts all requests.

NextJS
export function [1](req) {
  return new Response('Intercepted by middleware');
}
Drag options to blanks, or click blank then click option'
Acontroller
Bhandler
Crouter
Dmiddleware
Attempts:
3 left
💡 Hint
Common Mistakes
Using a different function name like 'handler' or 'router' which won't intercept requests.
2fill in blank
medium

Complete the code to check the request URL pathname in middleware.

NextJS
export function middleware(req) {
  const url = req.nextUrl;
  if (url.pathname === [1]) {
    return new Response('Home page intercepted');
  }
}
Drag options to blanks, or click blank then click option'
A'/'
B'/about'
C'/api/data'
D'/contact'
Attempts:
3 left
💡 Hint
Common Mistakes
Using a pathname like '/about' when intending to intercept the home page.
3fill in blank
hard

Fix the error in the middleware code to correctly rewrite the request to '/login'.

NextJS
import { NextResponse } from 'next/server';

export function middleware(req) {
  return NextResponse.[1]('/login');
}
Drag options to blanks, or click blank then click option'
Aredirect
Brewrite
Creplace
Dforward
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'redirect' when the goal is to rewrite the request internally.
4fill in blank
hard

Fill both blanks to create middleware that blocks access to '/admin' and redirects to '/login'.

NextJS
import { NextResponse } from 'next/server';

export function middleware(req) {
  const url = req.nextUrl;
  if (url.pathname === [1]) {
    return NextResponse.[2]('/login');
  }
}
Drag options to blanks, or click blank then click option'
A'/admin'
Bredirect
Crewrite
D'/dashboard'
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'rewrite' instead of 'redirect' which does not change the browser URL.
5fill in blank
hard

Fill all three blanks to create middleware that logs the request method, checks if the path is '/secret', and rewrites to '/login' if so.

NextJS
import { NextResponse } from 'next/server';

export function middleware(req) {
  console.log('Request method:', req.[1]);
  const url = req.nextUrl;
  if (url.pathname === [2]) {
    return NextResponse.[3]('/login');
  }
}
Drag options to blanks, or click blank then click option'
Amethod
B'/secret'
Crewrite
Dpathname
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'pathname' instead of 'method' to log the request method.
Using 'redirect' instead of 'rewrite' when internal path change is needed.