Next.js - API MiddleWares
Next.js - API Route Helpers and Request Parsing
Section titled “Next.js - API Route Helpers and Request Parsing”When working with API Routes in the Next.js Pages Router (files within pages/api), Next.js provides built-in helpers attached to the request (req) object to simplify common tasks like parsing incoming data.
These helpers act like pre-configured middleware:
req.cookies: An object containing the cookies sent by the request. Defaults to{}.req.query: An object containing the query string parameters. Defaults to{}.req.body: An object containing the request body, parsed based on theContent-Typeheader. If the header is not present or the body cannot be parsed, it defaults tonull. For example,application/jsonis parsed into an object, whileapplication/x-www-form-urlencodedis also parsed.
Note: In the App Router, you use Route Handlers instead of API Routes. The request object (NextRequest) provides methods like request.cookies.get('cookieName'), request.nextUrl.searchParams.get('paramName'), await request.json(), or await request.formData() to access similar information.
Let’s create a simple API Route example (Pages Router) demonstrating how to access query parameters and the request body.
Create a file named user.js inside the pages/api directory:
export default function handler(req, res) { // Access query parameters (e.g., /api/user?id=123) const { id } = req.query;
// Access request body (e.g., for POST or PUT requests) // The body is automatically parsed based on Content-Type const requestBody = req.body;
// Access request method const method = req.method;
if (method === 'GET') { // Handle GET request - maybe fetch user data based on id res.status(200).json({ message: `Fetching data for user ID: ${id || 'N/A'}`, query: req.query }); } else if (method === 'POST') { // Handle POST request - maybe create a new user res.status(201).json({ message: 'User created successfully!', receivedData: requestBody, query: req.query // Query params can exist on POST too }); } else { // Handle other methods or return an error res.setHeader('Allow', ['GET', 'POST']); res.status(405).end(`Method ${method} Not Allowed`); }}This example demonstrates accessing req.query for URL parameters, req.body for data sent in the request payload (like from a form submission or JSON POST), and req.method to handle different HTTP verbs.
Running the Development Server
Section titled “Running the Development Server”Make sure your development server is running:
npm run dev
# Example Output:# ready - started server on 0.0.0.0:3000, url: http://localhost:3000# event - compiled client and server successfully ...Verify Output
Section titled “Verify Output”- Test GET request with query parameters: Open your browser and navigate to
http://localhost:3000/api/user?id=456&source=web. You should see JSON output similar to:
{ "message": "Fetching data for user ID: 456", "query": { "id": "456", "source": "web" }}- Test POST request with a JSON body: You can use tools like
curl, Postman, or the browser’sfetchAPI to send a POST request. Usingcurlfrom your terminal:
curl -X POST http://localhost:3000/api/user?ref=test -H "Content-Type: application/json" -d '{"name": "Jane Doe", "email": "jane.doe@example.com"}'The expected JSON response would be:
{ "message": "User created successfully!", "receivedData": { "name": "Jane Doe", "email": "jane.doe@example.com" }, "query": { "ref": "test" }}This demonstrates how Next.js automatically parses the JSON body and makes it available via req.body, alongside the query parameters in req.query.