BPC
BPC

Reputation: 96

How to display custom 410 page with nextJs

I'm trying to handle 410 codes on my nextjs app. I've setup a 404 page already as it's easily managed by nextjs. But I can't figure out how to display a custom 410 page. I've tried to go through the _error page and check the httpStatusCode but it seems only to handle 5xx errors.

Is there a way to display a custom 410 page? And also, should I try to display a 410 page or only let the browser display the error (I'm not sure what is the best practice here)? I just did a "big" migration on my website and have a few 410 (not depending on me).

I can provide more information if needed Thanks

Upvotes: 2

Views: 2726

Answers (1)

brc-dd
brc-dd

Reputation: 13074

You can do something like this. The logic to check if a non-existing page should be responded with a 404 or 410 can be modified according to your need.

// _error.js

import Error from 'next/error';

const CustomError = ({ statusCode }) => (
  <Error
    statusCode={statusCode}
    title={
      statusCode === 410
        ? 'The requested resource is no longer available'
        : undefined
    }
  />
);

const gonePages = ['gone', 'moved', 'foo/bar'];

const compareURLs = (n, h) => {
  const nParts = n.split('/').filter(Boolean);
  const hParts = h.split('/').filter(Boolean);
  return (
    nParts.length <= hParts.length &&
    nParts.every((part, i) => part === hParts[i])
  );
};

const getServerSideProps = async ({ req, res }) => ({
  props: {
    statusCode:
      res.statusCode === 404 &&
      gonePages.some((slug) => compareURLs(slug, req.url))
        ? 410
        : res.statusCode,
  },
});

export default CustomError;
export { getServerSideProps };

Check the sandbox: codesandbox.io/s/zealous-driscoll-ru62j

Upvotes: 1

Related Questions