How to create a custom 403 forbidden page in Next.js



Image not found!!

In Next.js, you can create a custom 403 Forbidden page by utilizing the built-in error handling mechanism. Here are the steps to achieve this:

  1. Create a new file for your custom 403 page. For example, you can create a file named 403.js inside the pages directory.

    jsx
    // pages/403.js import React from 'react'; const ForbiddenPage = () => { return ( <div> <h1>403 Forbidden</h1> <p>Sorry, you don't have permission to access this page.</p> </div> ); }; export default ForbiddenPage;
  2. Utilize the Error component from Next.js to handle the 403 error. In your pages or components, you can throw a new Error with a statusCode of 403 when the user doesn't have the required permissions.

    jsx
    // Example: pages/some-protected-page.js import React from 'react'; const SomeProtectedPage = () => { // Check if the user has the required permissions const userHasPermission = false; if (!userHasPermission) { throw new Error('Forbidden'); } return ( <div> <h1>Protected Page</h1> <p>This page can only be accessed by users with the right permissions.</p> </div> ); }; export default SomeProtectedPage;
  3. Customize the error handling in the _error.js file (create one if it doesn't exist) to redirect to your custom 403 page.

    jsx
    // pages/_error.js import React from 'react'; import PropTypes from 'prop-types'; const ErrorPage = ({ statusCode }) => { return ( <div> <h1> {statusCode === 404 ? 'Not Found' : 'An Error Occurred'} </h1> {statusCode === 403 && ( <p>Sorry, you don't have permission to access this page.</p> )} </div> ); }; ErrorPage.getInitialProps = ({ res, err }) => { const statusCode = res ? res.statusCode : err ? err.statusCode : 404; return { statusCode }; }; ErrorPage.propTypes = { statusCode: PropTypes.number.isRequired, }; export default ErrorPage;

Now, when a user tries to access a protected page without the necessary permissions, they will be redirected to your custom 403 Forbidden page. Adjust the content and styling of the custom pages according to your needs.