0
0
NextJSframework~5 mins

Server-side error handling in NextJS

Choose your learning style9 modes available
Introduction

Server-side error handling helps catch and manage problems that happen on the server. It keeps your app running smoothly and shows friendly messages instead of crashing.

When fetching data from a database or external API on the server
When processing user input on the server before sending a response
When a server function might fail and you want to show a custom error page
When you want to log errors for debugging without stopping the app
When you want to return specific HTTP status codes for errors
Syntax
NextJS
export async function GET(request) {
  try {
    // server logic that might fail
    return new Response('Success', { status: 200 })
  } catch (error) {
    return new Response('Error message', { status: 500 })
  }
}

Use try...catch blocks to catch errors in server functions.

Return a Response with an appropriate status code to inform the client.

Examples
This example fetches data from an API and handles fetch errors gracefully.
NextJS
export async function GET(request) {
  try {
    const data = await fetch('https://api.example.com/data')
    if (!data.ok) throw new Error('Failed to fetch')
    const json = await data.json()
    return new Response(JSON.stringify(json), { status: 200 })
  } catch (error) {
    return new Response('Could not load data', { status: 500 })
  }
}
This example checks user input and returns a 400 error if validation fails.
NextJS
export async function POST(request) {
  try {
    const body = await request.json()
    if (!body.name) throw new Error('Name is required')
    // process data
    return new Response('Data saved', { status: 201 })
  } catch (error) {
    return new Response(error.message, { status: 400 })
  }
}
Sample Program

This server function always throws an error, which is caught and returned as a 500 response with the error message.

NextJS
export async function GET(request) {
  try {
    // Simulate a server error
    throw new Error('Server failed to process request')
  } catch (error) {
    return new Response(`Error: ${error.message}`, { status: 500 })
  }
}
OutputSuccess
Important Notes

Always handle errors to avoid crashing your server functions.

Use meaningful status codes like 400 for client errors and 500 for server errors.

Logging errors on the server helps find and fix issues faster.

Summary

Server-side error handling keeps your app stable and user-friendly.

Use try...catch blocks in server functions to catch errors.

Return proper HTTP status codes and messages to inform clients about errors.