How to Handle Errors in API Route in Next.js Correctly
In Next.js API routes, handle errors by wrapping your code in a
try-catch block and sending an appropriate HTTP status code with res.status() and an error message. This ensures your API responds clearly when something goes wrong instead of crashing or hanging.Why This Happens
When you don't catch errors in a Next.js API route, the server crashes or returns a generic 500 error without useful details. This happens because unhandled exceptions stop the function execution and leave the client without a clear response.
javascript
export default function handler(req, res) { // This code throws an error but does not catch it const data = JSON.parse('invalid json'); res.status(200).json({ data }); }
Output
SyntaxError: Unexpected token i in JSON at position 0
API route crashes and returns 500 Internal Server Error without a clear message.
The Fix
Wrap your API logic inside a try-catch block. In the catch, send a response with res.status(500) and a helpful error message. This way, the client knows what went wrong and the server stays stable.
javascript
export default function handler(req, res) { try { const data = JSON.parse('invalid json'); res.status(200).json({ data }); } catch (error) { res.status(500).json({ error: 'Failed to parse JSON' }); } }
Output
{"error":"Failed to parse JSON"}
Prevention
Always use try-catch blocks around code that can fail, like parsing JSON or calling external services. Return meaningful HTTP status codes (e.g., 400 for bad requests, 500 for server errors). Use logging to track errors and consider middleware for centralized error handling.
Related Errors
- Unhandled Promise Rejection: Use
async/awaitwithtry-catchto catch async errors. - Missing Response: Always send a response; forgetting
res.end()orres.json()causes hanging requests.
Key Takeaways
Wrap API route code in try-catch blocks to catch and handle errors.
Send clear HTTP status codes and error messages in the response.
Use meaningful status codes like 400 for client errors and 500 for server errors.
Always send a response to avoid hanging requests.
Consider logging errors for easier debugging and monitoring.