How to create a custom Error page in Next.js using TypeScript

How do I create an Error page in Next.js using Typescript?

I attempted the following:

interface ErrorProps {
  statusCode: number;
}
function Error({ statusCode }: ErrorProps) {
  return (
    <p>
      {statusCode
        ? `An error ${statusCode} occurred on the server`
        : "An error occurred on the client"}
    </p>
  );
}

interface InitialProps {
  res: NextApiResponse;
  err: NextApiResponse;
}
Error.getInitialProps = ({ res, err }: InitialProps) => {
  const statusCode = res ? res.statusCode : err ? err.statusCode : 404;
  return { statusCode };
};

However, I'm uncertain if this is the correct approach.

Answer №1

This code is functioning flawlessly as seen below. Give it a look!

For more information, visit the Next.js error page for typescript

import { NextPage, NextPageContext } from 'next';


interface Props {
    statusCode?: number
}

const Error: NextPage<Props> = ({ statusCode }) => {
    return (
        <p>
        {statusCode
            ? `An error ${statusCode} occurred on server`
            : "An error occurred on client"}
        </p>
    );
  }
  
  Error.getInitialProps = ({ res, err }: NextPageContext) => {
    const statusCode = res ? res.statusCode : err ? err.statusCode : 404
    return { statusCode }
  }
  
  export default Error

Answer №2

As per the documentation provided by Next ->

The pages/_error.js file is exclusively utilized in production. During development, an error message displaying the call stack will indicate the source of the error.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Tips on preventing Typescript error TS2531 related to potentially null objects

I'm working on retrieving the scroll position using the code snippet below: useEffect (()=>{ document.addEventListener("scroll", e => { let scrolled = document.scrollingElement.scrollTop; if (scrolled >= 5){ ...

I am trying to replace the buttons with a dropdown menu for changing graphs, but unfortunately my function does not seem to work with the <select> element. It works perfectly fine with buttons though

I am currently working on my html and ts code, aiming to implement a dropdown feature for switching between different graphs via the chartType function. The issue I am facing is that an error keeps popping up stating that chartType is not recognized as a ...

Guidelines for dynamically displaying <router-link> or <a> in Vue based on whether the link is internal or external

<template> <component :is="type === 'internal' ? 'router-link' : 'a'" :to="type === 'internal' ? link : null" :href="type !== 'internal' ? link : null" > <slot /> < ...

Decrease initial loading time for Ionic 3

I have encountered an issue with my Ionic 3 Android application where the startup time is longer than desired, around 4-5 seconds. While this may not be excessive, some users have raised concerns about it. I am confident that there are ways to improve the ...

Prohibit the utilization of application/json in a single request

Below is the code I have written to send a request for uploading a file: const uploadReq = new HttpRequest('POST', "https://localhost:44372/api/v1/Upload/UploadNewsPic" , formData, { reportProgress: true }); this.http.request(uploadReq).sub ...

How to refresh Google reCaptcha v3 in an Angular Firebase project

Recently, we encountered a problem with our application's signup process using OTP. We utilized Firebase phone authentication, which includes Google reCaptcha v3. While the OTP was sent successfully, we faced an error when attempting to change the pho ...

Fix the Typescript file by matching it with the folder name

Currently, I am in the process of converting my code from ES6 to .TS / .TSX. If we take a look at the folder structure below: Table/Tables.tsx In ES6, when importing from another React component, I was able to simply do this: import Table from '.. ...

What is the best way to change an existing boolean value in Prisma using MongoDB?

Exploring prisma with mongoDb for the first time and faced a challenge. I need to update a boolean value in a collection but struggling to find the right query to switch it between true and false... :( const updateUser = await prisma.user.update({ where: ...

What steps must be taken to resolve the error of setting headers after they have already been sent to the client?

Got a couple questions here. I've been using the express get method for a search query and it's fetching the requested tickets without any issues. However, I keep encountering errors even though the method itself is functioning properly. So, my f ...

Creating a dynamic table in HTML and Angular is a simple process that involves utilizing the

How can I create an HTML table dynamically without knowing the template of each row in advance? Sometimes it may have 2 columns, sometimes 4... I am looking for something like this: <div> <h1>Angular HTML Table Example</h1> < ...

``Can someone provide guidance on how to showcase the validation check result for a text-field in the snackbar using Vuet

One of the challenges I'm facing in my project is implementing a validation function for the customer form. While using the vuetify validate method would be the easy way to go, I need to display the validation messages both as snackbar and next to eac ...

Obtaining a list of dates for a particular week using React DayPicker

I'm seeking the ability to click on a specific week number within the react DayPicker and receive an array of all dates within that week. The DayPicker package I am using can be found here: I've copied the example code from react DayPicker to e ...

Can I retrieve the return type of useFetch in Nuxt3?

I am running into an issue while trying to specify the APIBody type in the following manner: Property 'test' does not exist on type 'NonNullable<PickFrom<_ResT, KeysOf>>'. It seems like there is no straightforward way to def ...

The CSS "mask" property is experiencing compatibility issues on Google Chrome

Hey there! I've recently developed a unique progress bar component in React that showcases a stunning gradient background. This effect is achieved by utilizing the CSS mask property. While everything runs smoothly on Firefox, I'm facing a slight ...

How to display the current date with the correct format using Angular 2?

I am trying to display the current date in the correct format, for example: 12/19/2016. I am currently using Date.now() but it is showing a garbage value. I only want to display the date without the time. I have also tried using pipes, but they are not b ...

The classification of rejected promises in Typescript

Is it possible to set the type of rejection for a promise? For example: const start = (): Promise<string> => { return new Promise((resolve, reject) => { if (someCondition) { resolve('correct!'); } else { ...

What steps should be taken to validate a condition prior to launching a NextJS application?

In my NextJS project (version 13.2.4), I usually start the app by running: npm run dev But there's a new requirement where I need to check for a specific condition before starting the app. If this condition is not met, the app should exit. The condi ...

Encountering "Invalid hook call" error with React Router while integrating Higher Order Components for authentication

Dealing with an error: React Router shows "Invalid hook call" with higher-order components for authentication Dilemma I have developed two distinct approaches for authentication wrappers in my React components with React Router. The first method functions ...

Exploring NextJS server-side development within a corporate proxy environment

As I develop server-side API's in NextJS, I encounter issues with fetching data from the Internet due to my development machine being behind a corporate proxy. While the target environment is in the cloud, the problem persists on my Mac OS X machine r ...

Angular2 Error: Issue with the "match" function in JavaScript

Why am I receiving a typeerror that says "cannot read property of 'match' undefined"? var numInput = document.getElementById('input'); // Listen for input event on numInput. numInput.addEventListener('input', function(){ ...