React / Next.js

Next.js API Routes

Route Handlers, GET/POST requests, middleware, CORS, authentication, error handling

20 interview questionsยท
Mid-Level
1

What is a Route Handler in Next.js 13+ with the App Router?

Answer

A Route Handler is a server function in a route.ts (or route.js) file that allows creating custom API endpoints. Unlike API Routes from the Pages Router (pages/api folder), Route Handlers are located in the app/ folder and support Web Standard Request/Response. They handle HTTP requests (GET, POST, PUT, DELETE, etc.) on the server side.

2

How to create a Route Handler to handle a GET request?

Answer

To handle a GET request, export an async function named GET in a route.ts file. This function receives a Request object and returns a Response using NextResponse.json(). Next.js automatically maps the exported GET function to HTTP GET requests on this route. Other HTTP methods (POST, PUT, DELETE, PATCH) follow the same pattern with their respective names.

3

What is the difference between NextResponse and standard Response?

Answer

NextResponse extends the standard Web Response class with Next.js-specific features. It provides convenient methods like NextResponse.json() for automatic serialization, NextResponse.redirect() for redirects, and makes cookie and header manipulation easier. While standard Response works, NextResponse is recommended as it simplifies code and offers better integration with the Next.js ecosystem.

4

How to retrieve search parameters (query params) in a Route Handler?

5

How to handle a POST request and retrieve the JSON body?

+17 interview questions

Master React / Next.js for your next interview

Access all questions, flashcards, technical tests, code review exercises and interview simulators.

Start for free