true not redirecting to 404 page when axios request fails

I have implemented Axios to access a basic API. My goal is to direct the user to the default Next.js 404 page in case of a failed request with a 404 error code. I have set the notFound boolean to true if the request status is 404. There are a total of 10 users available on the jsonplaceholder.typicode.com user API that I am utilizing. When I access the first 10 users, the request returns a 200 status and my page renders as expected. However, when attempting to access

https://jsonplaceholder.typicode.com/users/11
, for instance, instead of seeing the built-in 404 page, an unhandled error page is displayed.

import Link from 'next/link';
import axios from 'axios';

export async function getServerSideProps(ctx) {
  const { id } = ctx.query;
  const userReq = await axios.get(`https://jsonplaceholder.typicode.com/users/${id}`);
  if (userReq.status === 404) {
    return {
      notFound: true,
    };
  }
  return {
    props: {
      user: userReq.data,
    },
  };
}

function UserPage({ user }) {
  return (
   <div>
     <div>
       <Link href="/" passHref>
        Back to home
       </Link>
     </div>
     <hr />
     <div style={{ display: 'flex' }}>
      <div>
       <div>
         <b>Username:</b> {user.username}
       </div>
       <div>
         <b>Full name:</b>
         {user.name}
       </div>
       <div>
         <b>Email:</b> {user.email}
       </div>
       <div>
         <b>Company:</b> {user.company.name}
       </div>
       <div>
         <b>Phone:</b> {user.phone}
       </div>
      </div>
    </div>
  </div>
 );
}

export default UserPage;

Instead of being directed to the standard Next.js 404 page, I encounter an unhandled error: https://i.stack.imgur.com/4CrI4.png

I am unsure about the mistake I am making here. Any guidance or assistance would be greatly appreciated.

Answer №1

When Axios makes a request and receives a non-2xx response, it triggers an error. This error occurs before the execution of getServerSideProps, preventing the 404 page from being displayed.

To handle this situation, you need to encapsulate the axios call in a try/catch block and return the 404 page within the catch block instead.

export async function getServerSideProps(ctx) {
    const { id } = ctx.query;

    try {
        const userReq = await axios.get(`https://jsonplaceholder.typicode.com/users/${id}`);

        return {
            props: {
                user: userReq.data
            }
        };
    } catch(err) {
        console.error(err);

        return { 
            notFound: true 
        };
    }
}

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

"Learn the process of setting a variable in ng-model within an input field based on a specific condition

I need to dynamically assign an ng-model variable based on a condition. For instance: <input type="text" ng-model="item.model[multilang]" > The $scope.multilang variable can be set to either "ENG", "JP" (languages) or false. So, when multilang = "E ...

Where can content-tag and main-tag be found in vue-virtual-scroller?

I've been trying to wrap my head around the vue virtual scroller. I couldn't help but notice in the demo that it utilizes a few HTML attributes... <virtual-scroller v-if="scopedSlots" class="scroller" :item-height="itemHeight" :items="items" ...

Adding options for a select tag from JavaScript can be accomplished by using the DOM manipulation methods

I am working on a form that includes drop-down menus. The options for the select tag need to change dynamically based on the id value. For instance, if the id is 1, the select tag options should be cat and dog. If the id is 2, the options should be apple ...

Obtaining the ID from a JSON object in react.js ES6: A Comprehensive Guide

I have an array of JSON objects containing properties like Name, ID, and Address. My goal is to retrieve the IDs from all objects in this JSON array using react.js ES6. If anyone could offer guidance on how to accomplish this task, it would be greatly appr ...

Store the link in a variable and retrieve its content into another variable

Is there a way to extract the content of a link stored in a variable and store it in another variable using jQuery or javascript while working on an XML page? I know this is possible with php, but since I am developing a Chrome extension, I am wondering ...

Ensuring the timely execution of Javascript functions with Selenium before moving on

While working on creating test cases using Selenium, I encountered an issue. In one of my test cases, there is a small form and a search button on the website I'm testing. Filling the form and clicking the button are not the problem. The issue arises ...

Manipulate values within an array when a checkbox is selected or deselected

I am developing an Angular application where I have created a checkbox that captures the change event and adds the checked value to an array. The issue I am facing is that even if the checkbox is unchecked, the object is still being added to the array. D ...

Updating Angular Material theme variables during the build processIs this okay?

How can I easily customize the primary color of my angular 6 application to be different for development and production builds? Is there a simple solution to automatically change the primary color based on the build? ...

The subsequent block within the code is being initiated following the initial block in Node.js

It was expected that "1" would be printed before "2", but the output is incorrect. fs.readdir("./my_stocks", (err, files) => { for(each in files){ var file=files[each]; if(file!='portfolio.js'){ var fn="./my_sto ...

The next-routes server.js encounters an issue: TypeError - the getRequestHandler function is not defined within the routes

I encountered an issue in my server.js file. Here is the code snippet causing the problem: const { createServer } = require('http'); const next = require('next'); const routes = require('./routes'); const app = next ({ dev: ...

Discover the way to utilize the java enum toString() function in jQuery

In my Java Enum class called NciTaskType, I have defined two tasks: Pnd Review Woli and Osp Planning. public enum NciTaskType { PndReviewWoli, // 0 OspPlanning, // 1 ; @Override public String toString() { switch (this) ...

Utilize the Multer file upload feature by integrating it into its own dedicated controller function

In my Express application, I decided to keep my routes.js file organized by creating a separate UploadController. Here's what it looks like: // UploadController.js const multer = require('multer') const storage = multer.diskStorage({ dest ...

What steps can be taken to diagnose the cause of a failed Jquery AJAX request?

I am attempting to utilize the Yahoo Finance API to retrieve data in CSV format through Javascript. However, my current implementation shown below is not successful. $.ajax({ type: "GET", url: "http://finance.yahoo.com/d/quotes.csv?s=RHT+MSFT&f=sb2b3j ...

Adjust the loading bar component in Material UI to allow for customizable color changes

I am currently learning how to use material ui. My goal is to customize the loading bar's CSS. I checked the documentation and utilized colorPrimary classes. However, the changes are not appearing as expected. Could you please guide me on how to resol ...

Executing a function automatically when a component loads in react-redux can be achieved by utilizing useEffect hook in functional components

I have developed a webpage specifically designed to manage a "Cart" feature, with Cart details being fetched from a database. Upon clicking the "Click me" button, all the retrieved data is displayed within a react component. My goal now is to showcase the ...

Utilize Vue.js and express.js to distribute HTML files securely

Currently, my tech stack includes Vue.js for the frontend and Express.js for the backend. When I kick off the express.js server using npm start, my goal is to serve the Vue frontend component. By utilizing the Vue generator and Express generator, I attemp ...

Obtain the position and text string of the highlighted text

I am currently involved in a project using angular 5. The user will be able to select (highlight) text within a specific container, and I am attempting to retrieve the position of the selected text as well as the actual string itself. I want to display a s ...

How to effectively combine css() and delay() in jQuery?

fid: https://jsfiddle.net/k13sazuz/ Is there a way to create a delay chain for CSS rules using jQuery? $('.two').css('background','blue').delay(11800).css('background','red'); ...

What is the method for determining if a given point falls within a 3-dimensional cube?

I am currently seeking a method to determine whether a location is situated inside a rotated cube. To provide some context, I have access to the coordinates (x,y,z), rotation values (x,y,z), and dimensions (x,y,z). I am working with Javascript for this pr ...

Subscriber client successfully activated and operational via the command line interface

I have incorporated a script into my PHP file that reads the Pusher channel and performs various actions when a new event occurs on the specified channel. If I access the following URL in my browser: http:/localhost/pusher.php and keep it open, the p ...