How to automatically redirect empty routes to a specific route in Next.js

When visiting a non-existent endpoint in Next.js, I receive a 404 error. What I actually want is for all unused routes to automatically redirect to a default route; specifically, the landing page.

I've spent more than an hour trying to figure this out and I don't think it should be such a complex task. It seems like it should be straightforward.

So, I've decided to seek some help on this.

Thank you!

Answer №1

One way to handle 404 errors is by creating a custom page that redirects.

//src/pages/404.js
    
import React, { useEffect } from 'react'
import Router from 'next/router'


export default function Custom404() {

  useEffect(() => {
    Router.push('/')
  },[])

  return null
}

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

Steps for extracting URL parameters from AWS API Gateway and passing them to a lambda function

After successfully setting up my API gateway and connecting it to my lambda function, I specified the URL as {id} with the intention of passing this parameter into the lambda. Despite numerous attempts using both the default template and a custom one for ...

Creating a 301 Redirect in NextJS on Vercel - Step by Step Guide

Is there a way to create 301 redirects from one URL to another in NextJS application hosted on Vercel? I attempted to implement custom express server using server.js file but the redirects only function locally. Upon further research, I discovered this me ...

Is there a way to enhance the Download File dialog with an additional option?

I want to develop an extension for a specific file type, and I'm interested in including a "Send to MyAddonName" feature in the download file dialog, alongside the "Open with" and "Save file" options. Just to clarify, I don't mean the Download Ma ...

Display the properties of the nested object

I am trying to extract and print the postal_code value from the JSON file provided below: { "results" : [ { "address_components" : [ { "long_name" : "286", "short_name" : "286", "t ...

Transforming Thomas J Bradley's signature pad JSON into a PNG file using C# programming language

I have been experimenting with the Signature Pad plugin developed by Thomas J Bradley and successfully converted JSON signature to PNG using PHP. Now I am looking to achieve the same result using C#. There is a supplemental class called SignatureToImageDo ...

Strategies for increasing a value within an asynchronous function

I'm facing an issue with incrementing the variable loopVal inside a promise. I've tried to increment it without success. Any ideas on how to make this work? const hi = function(delay) { let loopVal = 1; return new Promise((resolve, reject) ...

Display header right button based on a condition in React Native using React Navigation

I am looking to conditionally display the Entypo new-message icon in the top right corner of the header based on a boolean variable (if true, then show the icon in the header). Here is a snippet of code where this functionality can be replicated. Thank y ...

Problems with select tag change events

I encountered an issue with select tag onChange events. When I select a value from the select tag, it should display in a textbox that is declared in the script. It works perfectly when I remove the class "input" from the select tag, but I prefer not to re ...

Put the code inside a function. I'm new to this

My goal is to encapsulate this code: if($(window).width() > 980) { $(window).on("scroll", function() { if($(window).scrollTop() > 20) { //add black background $(".x-navbar").addClass("active"); $(".x-navbar .desktop ...

The text is not displaying as expected due to a timeout issue

Trying to create a pop-up that functions as follows: After 3 seconds, the close button should appear, but during those 3 seconds, there will be a countdown. However, I'm encountering an issue where no text is being displayed. var n = 3; function p ...

Ensuring validity using dynamic context objects within Joi

I need to implement a dynamic validation system that involves downloading an object at runtime and saving it as a well-formed .json file. The objective is to use the values from this downloaded object as part of a validation process using Joi.validate wi ...

Tips for automatically incorporating animation upon page initialization

I'm looking to add an automatic image effect when the page is loaded. I currently have this code in my js file: $(window).ready(function(){ $(pin).click(function(){ $("#pin01").show().animate({left: '650px'}); }) }); Here is the HTML wit ...

Verify FileReader.onload function using Jasmine and AngularJS

I have a unique directive specifically designed for uploading and importing binary files. This directive listens for a change event on an <input type="file"../> element. Currently, I am facing an issue with the code coverage of my test. Although the ...

The process of flattening an array in Zustand: a comprehensive guide

In my array of brands, each brand object includes a brand name and products. Initially, I successfully added a new brand object to the brands list. However, when attempting to add another brand while keeping the previous brand data intact, it does not fu ...

Tips for uploading a file using Axios in a form

When uploading a file to a Flask server, I can access files from the flask request global by using raw HTML with the following code: <form id="uploadForm" action='upload_file' role="form" method="post" enctype=multipart/form-data> < ...

Which should take precedence in a URL: the hash or the querystring?

While some online articles suggest there is no standard for the placement of querystring and hash in a URL, we have continued to observe common practices. This leads to the question: what is the best approach for including both a querystring and hash in th ...

Issue with Mat-AutoComplete arising while utilizing a formArray

After adding a form array to account for multiple rows, I had to modify my definition from: shoppingCartList Observable<any[]>; to shoppingCartList: Observable<any[]>[] = [];. However, this change resulted in an error in my filter function whic ...

Tips for adjusting the color of a <a> tag upon clicking, which remains unchanged until the URL is modified

My goal is to maintain the color of a link when it is clicked. Currently, hovering over the navbar link changes it to greyish, but I want it to remain a different color after clicking on it. I am implementing this using the react-router-dom library for the ...

Is there a way to determine the names of the functions that are being called?

I'm working on mastering Google Development Tools. Is there a way to determine which specific functions, especially those in Javascript, are needed before a page can load successfully? ...

Using Jquery to duplicate a row from one table and insert it into another table

Recently, I've dived into the world of jQuery and JavaScript with the goal of creating a simple app. The main functionality I'm trying to implement is the ability to copy a row from one table to another and then delete the original row when a but ...