The infamous 404 error strikes again on Vercel Deployment, showcasing the power of dynamic routing in Next JS

I'm currently developing a full-stack web application using Next JS that allows users to create and manage letters (referred to as applications) based on predefined templates. Once the user successfully creates an application, it is stored in a POSTGRES database hosted on Supabase. The home page retrieves and displays the list of applications created by the user. When a user chooses to preview an application, dynamic routing is implemented using the application IDs as parameters. Using getStaticPaths() to fetch route parameters from the database and retrieving data for the page based on the application ID with the getStaticProps() method during build time, we render the page accordingly. While this setup functions smoothly on localhost, we encounter issues on Vercel. Interestingly, dynamic routing works seamlessly for past applications on Vercel in every deployment, allowing users to preview their previous applications without any issue. However, when attempting to preview a newly created application, users are faced with a 404 error. Triggering a manual redeployment or committing changes to the main branch resolves the error for the specific application causing the problem.

export const getStaticPaths = async () => {
  let APIendpoint;
  if (process.env.NODE_ENV === 'development') {
    APIendpoint = 'http://localhost:3000/api/fetchApplication'
  }
  else if (process.env.NODE_ENV === 'production') {
    APIendpoint = 'https://templaterepo.vercel.app/api/fetchApplication';
  }
  const data = await getPaths(APIendpoint)
  const paths = data.map((application) => {
    return {
      params: { id: application.appid.toString() }
    }
  })

 return {
    paths,
    fallback: 'blocking'
  }

}

export async function getStaticProps(context) {
  const appID = context.params.id;

  let APIendpoint;
  if (process.env.NODE_ENV === 'development') {
    APIendpoint = 'http://localhost:3000/api/fetchApplicationwithID'
  }
  else if (process.env.NODE_ENV === 'production') {
    APIendpoint = 'https://templaterepo.vercel.app/api/fetchApplicationwithID';
  }

  let data = await getPageData(APIendpoint, appID);
 
  return {
    props: { data }
  }
}

Below is the code for the dynamic [id].js page where I retrieve paths based on application IDs and fetch corresponding data at build time in the getStaticProps() function. While this functionality operates correctly on localhost, encountering a 404 error occurs prior to the execution of functions in Vercel deployments. Note: Vercel Framework Preset is configured for Next.js.

I've attempted several solutions, including adding href and as parameters in the Link component. Additionally, I modified my vercel.json file with the following configuration:

{
    "rewrites": [{ "source": "/(.*)", "destination": "/index.html" }]
}

Despite these efforts, the issue persists.

Answer №1

Users encounter a 404 error when they attempt to preview an application they have created. However, triggering a redeployment either manually or through a commit to the main branch of the repository resolves the error for that specific application.

This behavior is to be expected, as the data required for building each dynamic page is only fetched during the build process. By utilizing getStaticProps, you can incorporate ISR by including a revalidate prop in your getStaticProps. This way, if a page (such as a new application) has not been generated during build-time, Next.js will render it on the first request and cache it for subsequent requests.

In development mode, both getStaticProps and getStaticPaths are executed per request (similar to

getServerSideProps</code), which explains why this issue does not occur in the dev environment. See <a href="https://nextjs.org/docs/basic-features/data-fetching/get-static-props#runs-on-every-request-in-development" rel="nofollow noreferrer">documentation</a> for more information.</p>
<p>If you opt to implement ISR and wish to show a loading interface while the page is being server-rendered, ensure that you set <code>fallback: true
on getStaticPaths. You can then use the router.isFallback flag at the component level to display the appropriate loading UI, or stick with fallback: 'blocking' if it suits your current setup.

Furthermore, make sure to write your server-side code directly within getStaticProps and getStaticPaths, rather than calling your own API endpoints from these functions. Refer to the documentation for best practices.

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

Revise a function that locates an object with a corresponding id in an array, modifies a property, and updates a React component's state

Here is a function that takes in a rating value within an object. The ID and Question properties remain unchanged, but the rating value can be updated. This will result in updating a React state value. Is there a method to improve the readability and con ...

Modifying the HTML5 data attribute according to the URL hash

Within my div element, I have this code: <div id="nav-aj" data-options='{"default":'t1","animation": {"duration": 500, "effects": "fade"}}'> </div> I am looking to dynamically adjust the value of the default option based on th ...

Utilizing various colors for tooltipFontColor in Chart.js

I'm trying to customize the font color for tooltip labels in Chart.js, but I want to set different colors based on certain conditions. Specifically, I want the label color to be white by default, but change to red if a condition is met. I've look ...

What is the best way to navigate through images only when hovering?

I have a website that showcases a collection of images in a creative mosaic layout. Upon page load, I assign an array of image links to each image div using data attributes. This means that every image in the mosaic has an associated array of image links. ...

The symbol for ampersand and the symbol for number sign (& and #)

Special characters like ampersands and number signs are not being stored in my MS SQL database when I insert data. It seems to truncate the word after the ampersand or number sign. I am using an NVARCHAR column on MS SQL Server 2014. For instance, if I in ...

What is the best way to utilize document.body in order to add a table to a designated DIV?

Once I make a copy of the table, my goal is to insert this new table into a designated DIV named div1. How can I add the new table to div1? <div id="div1"> </div> var copiedElement = document.getElementsByTagName("table" ...

Upgrading ASP.Net MVC Web Application with the latest Bootstrap version 5

After updating Bootstrap from version 3.4.1 to 5.1.3, I encountered a similar issue as the original poster in this question. Thankfully, I was able to resolve it thanks to the provided answers. Now, when I click on the hamburger icon, the Navbar expands bu ...

Having issues with InstaFeed (search) feature and jQuery Mobile

As a new developer, I am working on my first JQM site. However, I am facing an issue with my search input form where the instafeed photos do not show up until after a manual page refresh following submission. Despite numerous attempts, I cannot seem to res ...

having difficulty altering a string in EJS

After passing a JSON string to my EJS page, I noticed that it displays the string with inverted commas. To resolve this issue, I am looking for a way to eliminate the inverted comma's and convert the string to UPPERCASE. Does anyone know how to achiev ...

Creating unique styles for components based on props in styled MUI: A comprehensive guide

One challenge I am facing is customizing the appearance of my component based on props, such as the "variant" prop using the 'styled' function. Here is an example code snippet: import { styled } from '@mui/material/styles'; const Remov ...

Please be patient until setInterval() completes its task

In order to add a dice-rolling effect to my Javascript code, I am considering using the setInterval() method. To test this out, I have come up with the following code: function rollDice() { var i = Math.floor((Math.random() * 25) + 5); var j = i; ...

The first argument in the Node.appendChild function does not adhere to the Node interface when trying to append to a new element

Hey there, I'm new to web development and could use some help. I'm encountering an error where I am trying to add an href attribute to an image tag. Here is my code: function linkus() { var a = document.getElementsByTagName("img"); ...

Toggle the tooltip to reveal a hidden div by clicking, and then click again to close it

I've been working on implementing a toggle div with a tooltip. The issue I'm facing is that the tooltip initially displays "Click to open", but after opening the toggle, it should change to "Click to close". Can someone assist me in achieving thi ...

Tips for incorporating external libraries into a Grafana data source plugin

What's the best way to integrate an external library into a Grafana datasource plugin? My plugin is functioning properly, but I encounter an error when trying to use the "mqtt" library that I have installed and added to the package.json file: Plugin ...

Adjusting the alignment of a React table of contents

I've designed a React + tailwind webpage featuring a table of contents that links to specific parts of the main article. However, I'm facing an issue with a sticky header of 100px that overlaps the content when the links are clicked (e.g. clickin ...

Tips on refreshing the D3 SVG element following updates to the dataset state in a React application

Hey everyone, I'm currently experimenting with D3.js and React in an attempt to build a dynamic dancing bargraph. Can anyone provide guidance on how to reload the D3 svg after updating the dataset state within REACT? Feel free to check out my codepen ...

Locating Undiscovered Users within mongodb

I have created a post collection where each user who marks a post as read has their user ID added to an array within the post document. Now, I am attempting to identify which users have not read certain posts by utilizing the $nin function while iteratin ...

Having trouble with JSFIDDLE not functioning properly on my website

I'm having an issue with implementing a JSFIDDLE on my web form. The fiddle itself is working perfectly fine, but for some reason, I can't get it to work on my page. Can someone please help me figure out what mistake I might be making? Here is th ...

When using the JavaScript .sort() method, any undefined value must always be considered as coming before any other value

I am working on sorting an array of objects based on multiple fields, typically around 3-4 fields. Some values within the objects may be undefined, and I need to ensure that these undefined values are considered as "earlier" in the sorting process, wheth ...

Having trouble with filtering the array retrieved from Firebase in Angular?

This is the html: <div ng-controller="FilterController as ctrl"> <div> All entries: <span ng-repeat="entry in ctrl.array">{{entry.from}} </span> </div> <div> Entries that contain an "a": & ...