Bird
Raised Fist0
NextJSframework~20 mins

Redirect and rewrite in middleware in NextJS - Practice Problems & Coding Challenges

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
Challenge - 5 Problems
🎖️
Middleware Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
component_behavior
intermediate
2:00remaining
What happens when this Next.js middleware redirects?

Consider this Next.js middleware code snippet:

import { NextResponse } from 'next/server';

export function middleware(request) {
  const url = request.nextUrl.clone();
  if (url.pathname === '/old-path') {
    url.pathname = '/new-path';
    return NextResponse.redirect(url);
  }
  return NextResponse.next();
}

What will the user see if they visit /old-path?

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

export function middleware(request) {
  const url = request.nextUrl.clone();
  if (url.pathname === '/old-path') {
    url.pathname = '/new-path';
    return NextResponse.redirect(url);
  }
  return NextResponse.next();
}
AThe browser URL stays '/old-path' and the content of '/old-path' is shown.
BThe browser URL stays '/old-path' but the content of '/new-path' is shown.
CThe browser URL changes to '/new-path' but the content of '/old-path' is shown.
DThe browser URL changes to '/new-path' and the content of '/new-path' is shown.
Attempts:
2 left
💡 Hint

Redirect changes the URL in the browser and sends a new request.

component_behavior
intermediate
2:00remaining
What is the effect of this rewrite in Next.js middleware?

Look at this middleware code:

import { NextResponse } from 'next/server';

export function middleware(request) {
  const url = request.nextUrl.clone();
  if (url.pathname === '/about') {
    url.pathname = '/company-info';
    return NextResponse.rewrite(url);
  }
  return NextResponse.next();
}

If a user visits /about, what will happen?

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

export function middleware(request) {
  const url = request.nextUrl.clone();
  if (url.pathname === '/about') {
    url.pathname = '/company-info';
    return NextResponse.rewrite(url);
  }
  return NextResponse.next();
}
AThe browser URL changes to '/company-info' but the content from '/about' is shown.
BThe browser URL stays '/about' but the content from '/company-info' is shown.
CThe browser URL stays '/about' and the content from '/about' is shown.
DThe browser URL changes to '/company-info' and the content from '/company-info' is shown.
Attempts:
2 left
💡 Hint

Rewrite changes the resource served without changing the browser URL.

📝 Syntax
advanced
2:30remaining
Which middleware code correctly performs a conditional redirect in Next.js?

Choose the code snippet that correctly redirects users from '/login' to '/dashboard' only if they are authenticated.

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

export function middleware(request) {
  const url = request.nextUrl.clone();
  const isAuth = request.cookies.get('auth')?.value === true;
  if (url.pathname === '/login' && isAuth) {
    url.pathname = '/dashboard';
    return NextResponse.redirect(url);
  }
  return NextResponse.next();
}
B
import { NextResponse } from 'next/server';

export function middleware(request) {
  const url = request.nextUrl;
  const isAuth = request.cookies.get('auth') === 'true';
  if (url.pathname === '/login' && isAuth) {
    url.pathname = '/dashboard';
    return NextResponse.redirect(url);
  }
  return NextResponse.next();
}
C
import { NextResponse } from 'next/server';

export function middleware(request) {
  const url = request.nextUrl.clone();
  const isAuth = request.cookies.get('auth')?.value === 'true';
  if (url.pathname === '/login' && isAuth) {
    url.pathname = '/dashboard';
    return NextResponse.redirect(url);
  }
  return NextResponse.next();
}
D
import { NextResponse } from 'next/server';

export function middleware(request) {
  const url = request.nextUrl.clone();
  const isAuth = request.cookies.get('auth')?.value === 'true';
  if (url.pathname === '/login' || isAuth) {
    url.pathname = '/dashboard';
    return NextResponse.redirect(url);
  }
  return NextResponse.next();
}
Attempts:
2 left
💡 Hint

Check how cookies are accessed and the condition logic.

🔧 Debug
advanced
2:30remaining
Why does this Next.js middleware cause a runtime error?

Examine this middleware code:

import { NextResponse } from 'next/server';

export function middleware(request) {
  const url = request.nextUrl.clone();
  if (url.pathname === '/profile') {
    url.pathname = '/user/profile';
    return NextResponse.rewrite(url);
  }
  if (url.pathname === '/dashboard') {
    return NextResponse.redirect('/home');
  }
  return NextResponse.next();
}

When visiting '/dashboard', the app crashes with an error. What is the cause?

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

export function middleware(request) {
  const url = request.nextUrl.clone();
  if (url.pathname === '/profile') {
    url.pathname = '/user/profile';
    return NextResponse.rewrite(url);
  }
  if (url.pathname === '/dashboard') {
    return NextResponse.redirect('/home');
  }
  return NextResponse.next();
}
ANextResponse.redirect() requires a URL object, not a string, causing a runtime error.
BThe middleware does not handle '/dashboard' correctly because '/home' does not exist.
CNextResponse.rewrite() cannot be used with '/user/profile' path.
DCloning the URL causes the error when redirecting from '/dashboard'.
Attempts:
2 left
💡 Hint

Check the argument type passed to NextResponse.redirect().

state_output
expert
3:00remaining
What is the final URL and content served after this complex middleware runs?

Given this Next.js middleware:

import { NextResponse } from 'next/server';

export function middleware(request) {
  const url = request.nextUrl.clone();
  if (url.pathname.startsWith('/blog')) {
    url.pathname = url.pathname.replace('/blog', '/news');
    return NextResponse.rewrite(url);
  }
  if (url.pathname === '/old-home') {
    url.pathname = '/home';
    return NextResponse.redirect(url);
  }
  return NextResponse.next();
}

If a user visits /blog/post-1 and then visits /old-home, what URLs will the browser show and what content will be served in each case?

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

export function middleware(request) {
  const url = request.nextUrl.clone();
  if (url.pathname.startsWith('/blog')) {
    url.pathname = url.pathname.replace('/blog', '/news');
    return NextResponse.rewrite(url);
  }
  if (url.pathname === '/old-home') {
    url.pathname = '/home';
    return NextResponse.redirect(url);
  }
  return NextResponse.next();
}
AVisiting '/blog/post-1' shows URL '/blog/post-1' with content from '/news/post-1'. Visiting '/old-home' changes URL to '/home' and shows '/home' content.
BVisiting '/blog/post-1' changes URL to '/news/post-1' and shows '/news/post-1' content. Visiting '/old-home' keeps URL '/old-home' but shows '/home' content.
CVisiting '/blog/post-1' changes URL to '/news/post-1' but shows '/blog/post-1' content. Visiting '/old-home' changes URL to '/home' but shows '/old-home' content.
DVisiting '/blog/post-1' keeps URL '/blog/post-1' and shows '/blog/post-1' content. Visiting '/old-home' keeps URL '/old-home' and shows '/old-home' content.
Attempts:
2 left
💡 Hint

Remember rewrite keeps URL, redirect changes URL.

Practice

(1/5)
1. What is the main difference between a redirect and a rewrite in Next.js middleware?
easy
A. Rewrite changes the URL in the browser, redirect does not.
B. Redirect changes the URL in the browser, rewrite does not.
C. Redirect and rewrite both change the URL in the browser.
D. Neither redirect nor rewrite affect the URL in the browser.

Solution

  1. Step 1: Understand redirect behavior

    A redirect sends the user to a new URL and updates the browser's address bar to that URL.
  2. Step 2: Understand rewrite behavior

    A rewrite changes the content served without changing the URL shown in the browser.
  3. Final Answer:

    Redirect changes the URL in the browser, rewrite does not. -> Option B
  4. Quick Check:

    Redirect updates URL, rewrite keeps URL same [OK]
Hint: Redirect changes URL; rewrite keeps URL same [OK]
Common Mistakes:
  • Thinking rewrite changes browser URL
  • Confusing redirect with rewrite
  • Assuming both always change URL
2. Which of the following is the correct way to perform a redirect in Next.js middleware?
easy
A. return NextResponse.redirect('/home');
B. return NextResponse.rewrite(new URL('/home', request.url));
C. return NextResponse.next('/home');
D. return NextResponse.redirect(new URL('/home', request.url));

Solution

  1. Step 1: Check NextResponse.redirect syntax

    The redirect method requires a full URL object, created with new URL(path, base).
  2. Step 2: Validate options

    return NextResponse.redirect(new URL('/home', request.url)); correctly uses new URL with request.url as base. return NextResponse.redirect('/home'); incorrectly passes a string instead of URL object.
  3. Final Answer:

    return NextResponse.redirect(new URL('/home', request.url)); -> Option D
  4. Quick Check:

    Redirect needs URL object [OK]
Hint: Use new URL(path, request.url) for redirects [OK]
Common Mistakes:
  • Passing string directly to redirect
  • Using rewrite instead of redirect
  • Missing base URL in new URL()
3. Given this middleware code snippet, what will happen when a user visits '/dashboard'?
import { NextResponse } from 'next/server';
export function middleware(request) {
  if (request.nextUrl.pathname === '/dashboard') {
    return NextResponse.rewrite(new URL('/profile', request.url));
  }
  return NextResponse.next();
}
medium
A. User sees content from '/profile' but URL stays '/dashboard'.
B. User is redirected to '/profile' and URL changes.
C. User stays on '/dashboard' with original content.
D. Middleware throws an error due to incorrect syntax.

Solution

  1. Step 1: Analyze rewrite usage

    The code uses NextResponse.rewrite to serve '/profile' content when URL is '/dashboard'.
  2. Step 2: Understand rewrite effect on URL

    Rewrite changes content served but keeps the browser URL unchanged as '/dashboard'.
  3. Final Answer:

    User sees content from '/profile' but URL stays '/dashboard'. -> Option A
  4. Quick Check:

    Rewrite changes content, not URL [OK]
Hint: Rewrite serves new content but keeps URL same [OK]
Common Mistakes:
  • Confusing rewrite with redirect
  • Expecting URL to change on rewrite
  • Assuming middleware throws error here
4. Identify the error in this middleware code that tries to redirect users from '/old' to '/new':
import { NextResponse } from 'next/server';
export function middleware(request) {
  if (request.nextUrl.pathname === '/old') {
    return NextResponse.redirect('/new');
  }
  return NextResponse.next();
}
medium
A. The condition should check request.url, not request.nextUrl.pathname.
B. Middleware must be async to use redirect.
C. Redirect requires a full URL object, not a string.
D. NextResponse.next() cannot be returned in middleware.

Solution

  1. Step 1: Check redirect argument type

    NextResponse.redirect expects a URL object, not a string path.
  2. Step 2: Validate other parts

    Condition and NextResponse.next() usage are correct; async not required here.
  3. Final Answer:

    Redirect requires a full URL object, not a string. -> Option C
  4. Quick Check:

    Redirect needs URL object, not string [OK]
Hint: Redirect needs new URL(path, request.url) [OK]
Common Mistakes:
  • Passing string directly to redirect
  • Making middleware async unnecessarily
  • Checking wrong request property
5. You want to redirect users to '/login' if they visit any page except '/public' or '/login'. Which middleware code correctly implements this logic?
hard
A. if (!['/public', '/login'].includes(request.nextUrl.pathname)) { return NextResponse.redirect(new URL('/login', request.url)); } return NextResponse.next();
B. if (['/public', '/login'].includes(request.nextUrl.pathname)) { return NextResponse.redirect(new URL('/login', request.url)); } return NextResponse.next();
C. if (request.nextUrl.pathname !== '/public' || request.nextUrl.pathname !== '/login') { return NextResponse.redirect(new URL('/login', request.url)); } return NextResponse.next();
D. if (request.nextUrl.pathname === '/public' && request.nextUrl.pathname === '/login') { return NextResponse.redirect(new URL('/login', request.url)); } return NextResponse.next();

Solution

  1. Step 1: Understand condition logic

    We want to redirect if the path is NOT '/public' or '/login'. Using !includes checks this correctly.
  2. Step 2: Check each option's condition

    if (!['/public', '/login'].includes(request.nextUrl.pathname)) { return NextResponse.redirect(new URL('/login', request.url)); } return NextResponse.next(); correctly uses negation with includes. if (['/public', '/login'].includes(request.nextUrl.pathname)) { return NextResponse.redirect(new URL('/login', request.url)); } return NextResponse.next(); redirects only on '/public' or '/login' which is wrong. Options C and D have logical errors in conditions.
  3. Final Answer:

    Option A code correctly redirects except for '/public' and '/login'. -> Option A
  4. Quick Check:

    Use !includes for exclusion check [OK]
Hint: Use !includes to exclude paths for redirect [OK]
Common Mistakes:
  • Using OR instead of AND in conditions
  • Redirecting on allowed paths
  • Incorrect logical negation