0
0
NextJSframework~5 mins

Error logging strategies in NextJS

Choose your learning style9 modes available
Introduction

Error logging helps you find and fix problems in your Next.js app quickly. It keeps track of what went wrong so you can improve your app.

When your Next.js app crashes or shows unexpected behavior.
When you want to know what errors users experience in production.
When debugging new features or changes in your app.
When monitoring app health and performance over time.
Syntax
NextJS
try {
  // code that might fail
} catch (error) {
  console.error('Error message:', error);
}

Use try...catch blocks to catch errors in your code.

console.error() prints error details to the terminal or browser console.

Examples
Catches errors when fetching data from an API and logs them.
NextJS
try {
  const data = await fetch('/api/data');
  const json = await data.json();
} catch (error) {
  console.error('Failed to fetch data:', error);
}
Logs errors in an API route and sends a 500 response.
NextJS
import { NextApiRequest, NextApiResponse } from 'next';

export default function handler(req, res) {
  try {
    // some code that may throw
    res.status(200).json({ message: 'Success' });
  } catch (error) {
    console.error('API error:', error);
    res.status(500).json({ error: 'Internal Server Error' });
  }
}
Logs errors differently based on environment: external service in production, console in development.
NextJS
if (process.env.NODE_ENV === 'production') {
  // send error to external service like Sentry
  Sentry.captureException(error);
} else {
  console.error(error);
}
Sample Program

This Next.js API route fetches data from an external API. If fetching fails, it logs the error and returns a 500 error response.

NextJS
import { NextApiRequest, NextApiResponse } from 'next';

export default async function handler(req, res) {
  try {
    const response = await fetch('https://jsonplaceholder.typicode.com/posts/1');
    if (!response.ok) {
      throw new Error('Network response was not ok');
    }
    const data = await response.json();
    res.status(200).json(data);
  } catch (error) {
    console.error('Fetch error:', error);
    res.status(500).json({ error: 'Failed to load data' });
  }
}
OutputSuccess
Important Notes

Always log enough details to understand the error but avoid sensitive data.

Use external error tracking tools like Sentry or LogRocket for production apps.

Console logs are helpful during development but may be removed or redirected in production.

Summary

Error logging helps find and fix problems fast.

Use try...catch and console.error() to log errors.

Consider external services for better error tracking in production.