[Solved] How do i define an api route in next js 14? – Rest

by
Alexei Petrov
django-rest-framework next.js

Quick Fix: To define an API route in Next.js 14, ensure that you include the Response object in the method definition. Update your code to include Response as shown: export function GET(req: NextApiRequest): Response { return Response.json({ message: 'Hello from Next.js!' }) }

The Problem:

I’m facing an issue while defining an API route in Next.js 14. When I try to call the API endpoint, I receive a TypeError stating that ‘res.status’ is not a function. I’m using the App Router along with TypeScript version 5.1.3 and Next.js version 14.0.3. Additionally, placing the API route inside the pages folder as per the Page Router method did not resolve the issue.

The Solutions:

Solution 1: Use Response object in API route handler

To define an API route in Next.js 14, create a file inside the src/app/api directory. For example, let’s consider a file named route.ts in src/app/api/timetable.

In route.ts, define your API route handler function using the syntax export function GET(req: NextApiRequest, res: NextApiResponse) {}.

The GET function is a request handler function that handles GET requests to the specified endpoint. It takes two parameters: req (the Next.js request object) and res (the Next.js response object).

Inside the GET function, you can use res.status() to set the HTTP status code and res.json() to send a JSON response.

However, there is a common mistake that can lead to an error. If you define the GET function as export function GET(req: NextApiRequest, res: NextApiResponse<ResponseData>) {}, you need to use return Response.json({ message: ‘Hello from Next.js!’ }) to send a response.

In this case, Response is a class from the next module, and Response.json() is a method that sends a JSON response. If you omit Response, you will get an error because res.json() is not a function.

Therefore, ensure that you use Response.json() correctly when defining an API route handler function in Next.js 14.

Here is an example of a corrected route.ts file:

import { NextApiRequest, NextApiResponse } from 'next';

type ResponseData = {
  message: string
}

export function GET(req: NextApiRequest): Promise<NextApiResponse<ResponseData>> {
  return Response.json({ message: 'Hello from Next.js!' })
}

With this correction, you should be able to successfully call the API endpoint at localhost:3000/api/timetable and receive the JSON response.

Solution 2: Response.json({Msg:”your message”}, {status:200});

This is a JavaScript solution that uses the Response object to send a JSON response with a custom status code. Here’s a more detailed explanation:

  • Use the Response Object: To send a response to a request, you need to use the Response object. This object contains methods and properties that allow you to define the response status code, headers, and body.
  • Set the Response Status Code: In this case, the status code is set to 200, which indicates a successful request. You can set other status codes, such as 404 (Not Found) or 500 (Internal Server Error), depending on the situation.
  • Set the Response Headers: This example doesn’t set any response headers, but you can use the Response object to set custom headers if needed.
  • Send the Response Body: The response body is an object with a Msg property that contains the message you want to send back to the client. You can also include other properties in the response body if needed.
  • Use the json() Method: The json() method on the Response object converts the JavaScript object into a JSON string and sets the Content-Type header to application/json.

To use this solution, you would need to import the Response object from the appropriate module, such as next/dist/server/web/spec-compliant/fetch-event, and then use it to send your response.

Here’s an example of how you might use this solution in your code:

“`
import { Response } from ‘next/dist/server/web/spec-compliant/fetch-event’;

export function GET(req, res) {
const response = new Response(JSON.stringify({ Msg: ‘your message’ }), {
status: 200,
});
res.send(response);
}

Solution 3: Using NextResponse in Next.js 14

In Next.js 14, the `NextApiRequest` and `NextApiResponse` classes have been replaced with `Request` and `NextResponse`. To define an API route in folder structure like `src/app/api/timetable`, follow these steps:

  1. Create a file named `route.js` inside the `src/app/api/timetable` directory.
  2. Import the `NextResponse` class from the `next/server` module.
  3. Define an exported async function named `GET`.
  4. Inside the `GET` function, use the `NextResponse.json()` method to return a JSON response.

Here’s an example of a route file using NextResponse:

// app/api/timetable/route.js
import { NextResponse } from 'next/server';

export async function GET(request: Request) {
  return NextResponse.json({ message: 'Hello from Next.js!' });
}

Remember to refer to the Next.js documentation for more details and examples:

With this approach, you can define API routes in a structured manner within your Next.js 14 application.

Video Explanation:

The following video, titled "Next.js Middleware & Cors | Nextjs 13 tutorial - YouTube", provides additional insights and in-depth exploration related to the topics discussed in this post.

Play video

How to Build a REST API with Next.js 13. Dave Gray•80K views · 20:37 · Go to ... API Routes with Next.js 14 — Course part 10. Codewithguillaume• ...