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

The Apollo Client Context does not support headers

I have implemented a cookie-based authentication system in my application. Below is the code snippet I am using to authenticate my requests: import { HttpLink } from "@apollo/client"; import { setContext } from "@apollo/client/link/context&q ...

MS Edge modifies the attribute's empty value to 1

I have written a JavaScript code to extract values from a list, but in the Windows Edge browser, it returns a value of 1 even when the actual value of the <li> tag is blank. For example: HTML Code <ul> <li value="">Test 1</li&g ...

Send a variable from a next.js middleware to an API request

I've been attempting to pass a middleware variable to my API pages via "req" but have encountered some issues Even after trying to send the user token to pages using "req", it consistently returns null The middleware file in question is: pages/api/u ...

Unlawful use of the return statement

Can you identify the issue with this code? The browser reports: "Uncaught SyntaxError: Illegal return statement" I'm looking for an explanation in this format: 1 2 3fool 4 5bar 6fool 7 8 9bar... let arr = []; for (i = 0; i <= 100; i++) { if ( ...

Challenges faced when trying to execute a next.js project on a server

I am currently facing an error while attempting to run a basic test project on a Linux server using next.js. The project runs without any issues locally, but whenever I try to execute either npm run dev or npm run build, I encounter the following error mes ...

Encountered a problem when injecting the angularjs $location service

I'm having some trouble getting the $location service to work in this code snippet: <script type="text/javascript> var $injector = angular.injector(['ng', 'kinvey', 'app.constants']); $in ...

What is the process of using a For loop to output a string in reverse order?

I'm attempting to reverse the string "hello" using a For loop, aiming for the output of "olleh". However, I'm facing an issue where the last character in the string is not being removed after being added to the array. Consequently, only the last ...

What are the best methods for profiling a Node.js application at a specific point in its execution?

I am currently facing performance issues with my Node application, which listens to a websocket data feed and communicates with another API. The CPU usage is normally stable at around 2-5%, but occasionally (approximately 3 times within 24 hours) the incom ...

What distinguishes res.send from app.post?

I'm just starting to learn about express and HTTP. I've heard that the express library has app.get, app.post, and res.send methods. From what I gather, app.get is used for GET requests and app.post is used for POST requests. How does res.send fit ...

Mongoose Filtering in Rest API: A Comprehensive Guide

Currently, I am utilizing Express to construct an API. Within this API, my objective is to retrieve a list of customers from MongoDB by using Mongoose. The code snippet below showcases the route I have set up (please disregard any paging and limit concerns ...

"Put Phonegap on hold for a bit and disable landscape mode

I am currently using Phonegap to develop an Android game. My project includes a lobby feature where players can search for opponents and engage in chat with other players. Once a player has found their opponent, they can commence playing the game together ...

Is anyone else experiencing differences in the appearance of my mega menu between Safari, Firefox, and Chrome? It seems like

When viewing in Safari, the text overlaps for some reason. It works fine on Firefox and Chrome. Here's a screenshot of the issue: Safari: https://i.stack.imgur.com/hf7v2.png Firefox: https://i.stack.imgur.com/NrOOe.png Please use Safari to test th ...

Is there an undocumented property lurking in the depths of the Webpack server

The document specifies that Options that work with webpack-dev-middleware will have a key symbol next to them. I couldn't find any information on "cookieDomainRewrite" but when I tried using it, it worked. Any insights? Or suggestions on how I ...

JavaScript Execution Sequence: Demystifying the Order of Operations

I am struggling to comprehend the order of execution in the following code snippet. It is a portion of a larger script, but it all begins with $( "#select-overlay" ). function findSelectedMap(mapID) { $.getJSON('maps.json', function (json) { ...

Firefox triggers drag events while passing over a div scrollbar

I am looking to create a file drag and drop feature using a styled div: When dragging files over the div, I want the border color to change When dragging files out of the div, I want the border color to revert back to the original In Firefox 35 (Ubuntu) ...

Is there a way to access the Google Maps instance without the need to define it as a global variable?

When referencing the google map API documents, it is common practice to use script tags which make the google map instance a global variable. But is there a way to access the map instance without it being global? The npm/bower package angular-google-maps, ...

Shorten Text - React Native

I currently have a React Native application with a FlatList component. The logic I initially implemented was to display an Expand/Collapse arrow whenever the content at the 100th position in the list is not empty. However, I now realize that this approach ...

Encountering an issue with disabling certain ESLint rules during the build process of a Next.js application

Trying to deploy my Next.js file on the server, but encountering an error when running npm run build. Struggling with ESLint rules? Find help here: https://nextjs.org/docs/basic-features/eslint#disabling-rules The application works fine on localhost, bu ...

Tips for fading an image as you scroll using CSS and JavaScript?

I have been dedicating my day to mastering the art of website development. However, I am facing a challenge that is proving to be quite difficult. I am looking to create a smooth transition effect where an image gradually blurs while scrolling down, and re ...

Is it possible to modify the inline onkeyup function?

Looking for a solution to change the onkeyup function in a textarea element from 255 characters to 150 characters without directly editing the code? <textarea cols="50" rows="4" id="textbox" onkeyup="limitArea(this, 255, '')"></textarea ...