Skip to content

Instantly share code, notes, and snippets.

@tiptopcoder
Last active April 17, 2023 10:26
Show Gist options
  • Save tiptopcoder/ee56b81e1d8e0a7e79b755b2d60b72fd to your computer and use it in GitHub Desktop.
Save tiptopcoder/ee56b81e1d8e0a7e79b755b2d60b72fd to your computer and use it in GitHub Desktop.
Next.js Typescript error page
import { NextPageContext } from "next";
const Error = ({ 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;
@tim1uphealth
Copy link

how would you type the return type for the Error function?

@ediblecode
Copy link

@tim1uphealth you mean like this?

import { NextPageContext } from "next";

interface ErrorComponentProps {
	statusCode?: number;
}

function ErrorComponent({ statusCode }: ErrorComponentProps): JSX.Element {
	return (
		<p>
			{statusCode
				? `An error ${statusCode} occurred on server`
				: "An error occurred on client"}
		</p>
	);
}

ErrorComponent.getInitialProps = ({ res, err }: NextPageContext) => {
	const statusCode = res ? res.statusCode : err ? err.statusCode : 404;
	return { statusCode };
};

export default ErrorComponent;

@brandoncroberts
Copy link

NextPage TypeScript type on the component seems to handle everything.

import { NextPage } from 'next';
const Error: NextPage = () => {......}
Error.getInitialProps = ({ res, err }) => {.....};
export default Error;

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment