404 Not Found — /api/hello
500 Internal Server Error
TypeError: res.json is not a function
Your Next.js API route isn’t working. The cause depends on whether you’re using the Pages Router or App Router.
Fix 1: Wrong File Location
# Pages Router: must be in pages/api/
pages/api/hello.js # ✅ /api/hello
src/pages/api/hello.js # ✅ If using src/
# App Router: must be route.ts in app/api/
app/api/hello/route.ts # ✅ /api/hello
app/api/hello.ts # ❌ Wrong — needs route.ts
Fix 2: App Router — Wrong Export
// ❌ Pages Router syntax in App Router
export default function handler(req, res) { // 💥
res.json({ hello: 'world' });
}
// ✅ App Router uses named exports
export async function GET() {
return Response.json({ hello: 'world' });
}
export async function POST(request: Request) {
const body = await request.json();
return Response.json({ received: body });
}
Fix 3: Method Not Allowed
// ❌ Only exported GET but sending POST
export async function GET() { ... }
// POST /api/hello → 405
// ✅ Export the methods you need
export async function GET() { ... }
export async function POST() { ... }
Fix 4: Middleware Blocking
// ❌ middleware.ts blocking API routes
// middleware.ts
export function middleware(request) {
// Redirecting everything including /api/*
}
// ✅ Exclude API routes
export const config = {
matcher: ['/((?!api|_next/static).*)'],
};
Fix 5: Environment Variables Not Available
// ❌ Using NEXT_PUBLIC_ prefix for server-side secrets
const key = process.env.NEXT_PUBLIC_API_SECRET; // Exposed to client!
// ✅ Server-side env vars don't need prefix
const key = process.env.API_SECRET; // Only available in API routes