API Route Errors
Server-side vs Client-sde API Fetch Route
When making a fetch request to a /api
route in server-side
component, the target URL has to be prepended with full origin address http://localhost:3000/
.
- Server-side component does not know the current base URL from where the fetch request is being made from.
- Unlike client-side component which knows the base URL of the current webpage.
# client side fetch URL address /api/domain_name/resource # server-side fetch URL address http://localhost:3000/api/domain_name/resource
API Routes Response Size Limited to 4MB
API Route
is limited to send a response
that is less than 4MB
.
API Routes
in NextJS are designed to deliver quick responses and are not built to support the transmission of large amounts of data.
If you must send API response greatker than the limit, you have to increase the limit via the responseLimit
config.
405
Method Not Allowed
This is caused by export function in /api
route being either one of two things:
- there is a
default export
instead of individual export for HTTP methods likeexport async function POST()
- you've named the exported function something other than the HTTP methods like
GET
,POST
,PUT
,DELETE
, andOption
CORS
Error to /api
endpoint
This is caused by missing CORS config on /api/route.ts
import { NextResponse } from "next/server"; export async function OPTIONS(request: Request) { const allowedOrigin = request.headers.get("origin"); const response = new NextResponse(null, { status: 200, headers: { "Access-Control-Allow-Origin": allowedOrigin || "*", "Access-Control-Allow-Methods": "GET, POST, PUT, DELETE, OPTIONS", "Access-Control-Allow-Headers": "Content-Type, Authorization, X-CSRF-Token, X-Requested-With, Accept, Accept-Version, Content-Length, Content-MD5, Date, X-Api-Version", "Access-Control-Max-Age": "86400", }, }); return response; }
404
Page Not Found
When you get a 404
response on an api route call when multiple HTTP methods coexist on a route
file
- The root cause is that the new method added has an invalid code (e.g. filesystem path reference)
- When one bad method is introduced to the
route
file, other methods that were previously working will also break