0
0
NextJSframework~10 mins

Request modification in NextJS - Interactive Code Practice

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

Complete the code to modify the request method to POST in a Next.js API route.

NextJS
export async function handler(req, res) {
  if (req.method === '[1]') {
    res.status(200).json({ message: 'Success' });
  } else {
    res.status(405).end();
  }
}
Drag options to blanks, or click blank then click option'
APOST
BGET
CPUT
DDELETE
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'GET' instead of 'POST' for modifying data.
2fill in blank
medium

Complete the code to read JSON data from the request body in a Next.js API route.

NextJS
export async function handler(req, res) {
  if (req.method === 'POST') {
    const data = await req.[1]();
    res.status(200).json({ received: data });
  } else {
    res.status(405).end();
  }
}
Drag options to blanks, or click blank then click option'
Atext
Bjson
CformData
Dblob
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'text' instead of 'json' to parse JSON data.
3fill in blank
hard

Fix the error in the code to correctly modify the request headers in a Next.js middleware.

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

export function middleware(req) {
  const res = NextResponse.next();
  res.headers.set('[1]', 'application/json');
  return res;
}
Drag options to blanks, or click blank then click option'
AContent-Type
BAuthorization
CAccept
Dcontent-type
Attempts:
3 left
💡 Hint
Common Mistakes
Using lowercase 'content-type' which might cause issues in some environments.
4fill in blank
hard

Fill both blanks to correctly clone and modify the request URL in Next.js middleware.

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

export function middleware(req) {
  const url = req.nextUrl.clone();
  url.[1] = '/new-path';
  return NextResponse.rewrite(url.[2]);
}
Drag options to blanks, or click blank then click option'
Apathname
Bhref
Corigin
Dsearch
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'origin' or 'search' instead of 'pathname' or 'href'.
5fill in blank
hard

Fill all three blanks to correctly modify request headers and method in Next.js middleware.

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

export function middleware(req) {
  const newHeaders = new Headers(req.headers);
  newHeaders.set('[1]', 'application/json');
  const newRequest = req.clone({
    method: '[2]',
    headers: newHeaders
  });
  return NextResponse.next({ request: newRequest, [3]: true });
}
Drag options to blanks, or click blank then click option'
AContent-Type
BPOST
CwaitUntil
Dcache
Attempts:
3 left
💡 Hint
Common Mistakes
Using wrong header names, wrong method names, or incorrect middleware options.