Next.js ensures that dynamic routes do not result in redirection to a 404 page

I am facing an issue with my Next.js project. I have a file named [pid].js and I also want to add a custom 404 page. However, when I place the 404.js file inside the /pages directory, it causes a problem. If I remove the [pid].js file, the 404 page works fine. But, if I keep the [pid].js file, the first request goes into pids and since the URL does not match any of the pages defined in pids, I encounter an error. Should I explicitly return my 404 component from pids? Is this considered good practice?

The current code snippet (which does not redirect to the 404 page):

[pid].js

const Pid = ({ url, props }) => {
    const getPages = () => {
        let component = null;
        switch (url) {
            case 'checkout':
                component = <CheckoutPage {...props} />;
                break;
            //other switch cases...
            default:
                //should I return my 404 component here?
                component = <DefaultPage {...props} />;
        }
        return component;
    };

    return getPages();
};

export async function getServerSideProps(context) {
    const res = await getReq(`/getUrl`, 'content', context);

    switch (res.url) {
        case 'checkout': {
            return {
                props: {
                    url: res.url,
                    props: {
                    ... //my other props
                    },
                },
            };
        }
        default:
            return {
                props: null,
            };
    }
}

Pid.propTypes = {
    url: PropTypes.string.isRequired,
};

export default Pid;

Answer №1

A new feature in NextJS 10 allows you to avoid explicitly returning your 404 page by using the notFound: true flag. This can be utilized in both getStaticProps and getServerSideProps to automatically trigger either the default 404 page or a custom one of your own.

For examples, refer to the NextJS Docs below:

export async function getStaticProps(context) {
  const res = await fetch(`https://.../data`)
  const data = await res.json()

  if (!data) {
    return {
      notFound: true,
    }
  }

  return {
    props: { data }, // will be passed to the page component as props
  }
}
export async function getServerSideProps(context) {
  const res = await fetch(`https://...`)
  const data = await res.json()

  if (!data) {
    return {
      notFound: true,
    }
  }

  return {
    props: {}, // will be passed to the page component as props
  }
}

Documentation References:

  1. Support for notfound on Nextjs10

  2. Using notfound with getStaticProps

  3. Implement notfound with getServerSideProps

  4. Creating a Custom 404 Page

Answer №2

Starting from version 10 of Next.js, you have the ability to use notFound: true in your getServerSideProps function to display a custom 404 error page.

export async function getServerSideProps(context) {
    const res = await getRequest(`/fetchData`, 'data', context);
    switch (res.url) {
        case 'login': {
            return {
                props: {
                    //additional properties
                },
            };
        }
        default:
            return {
                notFound: true
            };
    }
}

I've included it in the default case as an illustration, but you can implement it at any other point or condition as needed.

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 for hiding a popover in Angular when clicking outside of it

In a demo I created, rows are dynamically added when the user presses an "Add" button and fills in a name in an input field. Upon clicking "OK," a row is generated with a Star icon that should display a popover when clicked. While I have successfully imple ...

The function element.innerHTML is invalid when trying to assign an object value as an option

Hey there! I'm currently working on a JavaScript project where I have an input that retrieves text from an array. Each option in the array needs to be linked to an object so I can utilize its attributes. const data = [ { name: "SIMPLES NACION ...

The absence of a type annotation for `T` has been noted

Attempting to create code with a simple JavaScript function: filterArray(user: any, items: Array<Object>) { items = items.filter(item => {return true;}); return items; } Encountering the following error: Error message: Missing type anno ...

The use of JavaScript within the code results in the <header> and <nav> elements failing to display on the browser

Currently, I am tackling a webpage project that involves using scripts in both the head and section elements to generate a table where clicking on the cells changes their color randomly. However, a glitch seems to be hindering the display of the header and ...

Enhance the appearance of your custom three.js Geometry by incorporating different textures

I have been struggling to implement UV-mapping on my custom geometry in three.js. Despite trying various solutions, none seem to be working. Can someone provide a clear explanation of how UV-mapping functions and the correct way to implement it? var s = 1 ...

Retrieve information from Angular service's HTTP response

Calling all Angular/Javascript aficionados! I need some help with a service that makes API calls to fetch data: app.service("GetDivision", ["$http", function($http){ this.division = function(divisionNumber){ $http.post("/api/division", {division:di ...

The interval becomes congested due to the execution of two simultaneous Ajax calls

I have an Interval set to run a function every 3 seconds. intervalStepper = window.setInterval('intervalTick()','3000'); function intervalTick() { if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari ...

Javascript deepmerge causes issues with objectid manipulation

While I have experience with javascript, using node.js for the first time has presented some challenges. I am attempting to form a basic query to be used in mongoose, with the intention of adding conditions later on. I am currently employing deepmerge to m ...

Tabulate the number of items in an array based on the month and

I have received JSON data with dates indicating the creation time of multiple parcels. I want to analyze this data and calculate the total number of parcels created in each month. I am new to this process and unsure about which thread on Stack Overflow can ...

What is the most effective method for setting up numerous instances in AWS to run a unique Next.js application?

In my Next.js app, I am utilizing custom server options and AWS CodePipeline for CI/CD. The pipeline includes CodeBuild to build the app and AWS CodeDeploy to deploy it to all instances in an autoscaling group. This deployment is configured with CodeDeploy ...

Please enter a number to exclusively accept whole numbers with the use of the addEventListener method

My goal is to create an HTML input field that only allows entry of numbers between 1 and 999, with a maximum length of 3 characters. However, I am facing an issue with decimal numbers being accepted in the input. How can I restrict the input to only accept ...

Utilize dependency injection to connect services with controllers located in separate files

In my storage.js file, I have defined a controller and service as follows: angular.module('app', []). controller('storageController', ['$scope', 'storage', function ($scope, storage) { ...

Import and load numerous JSON files into a responsive and visually appealing Bootstrap table

I am new to coding in javascript and I'm seeking assistance in loading multiple JSON files to populate a bootstrap table. Currently, I've managed to create a table by manually combining the content from different files into one variable called l ...

Connecting Vue.js components together

I have two separate components - one for viewing data and another for editing the same data. The viewing component contains labels and paragraphs, while the editing component includes inputs and textareas. Both components are fed the same data object. Is ...

Angular - The connections between deeply nested object models are established

I have an Angular application that is used to display company and contact person information in a text box format. Here is the code for displaying the Company Email address: <label> Company Email address</label> <input type="text& ...

Transferring a Picture via GupShup

Having trouble sending an image through GupShup using their sandbox environment. My backend utilizes node.js with feathersjs framework, but I keep encountering this error: Response { size: 0, timeout: 0, [Symbol(Body internals)]: { body: PassThro ...

What is the best way to import a JavaScript file from an outside source or directory without encountering any path complications?

What is the best way to import a module from a different directory without encountering path problems? For instance, in the file src/index.js, there is a require('../other/main') statement. An error occurs due to the fact that in the main.js fi ...

What is the best way to limit an input field to only allow up to two decimal places and a maximum of 10 total

Is there a way to limit an input field to only accept two decimal places and have a maximum of 10 digits? I have implemented a function that is triggered by the onkeypress event and checks the length of the value entered into the input field. I have manag ...

Challenges encountered while using Selenium WebDriver to upload images

I'm having trouble adding an image as a normal attachment to an email (not as an inline image). When inspecting the HTML DOM with Firebug, I noticed there are two elements with xpath //input@type='file', which is due to the presence of two b ...

Displaying error message dynamically using ajax

I am looking to customize the way error messages are displayed on my form. Instead of having one generic div above the whole form, I want the error messages to appear next to each input field. <div id="response"><!--This section will show error ...