πŸ”§ Error Fixes
Β· 1 min read

Next.js API Route Not Working β€” How to Fix It


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

Related: What is Next.js Β· Turbopack Not Supported Fix

πŸ“˜