"Encountering a 404 error on newly published content, post build phase, with the integration of Next

My main objective is to enable the addition of new posts to the CMS (Sanity.io) post-build, and have the website display the received data on a designated slug through dynamic routes.

While everything functions smoothly in the development environment, I encounter an issue in production where the page fails to utilize the new slugs from the CMS, resulting in a 404 error.

Below is the snippet of code responsible for fetching posts from the CMS within my [slug].tsx file:

[slug.tsx]

export const getStaticPaths: GetStaticPaths = async () => {
  const query = `
  *[_type=='post']{
    _id,
    slug {
      current
    }
  }`

  const posts = await sanityClient.fetch(query)

  const paths = posts.map((post: Post) => ({
    params: {
      slug: post.slug.current,
    },
  }))

  return {
    paths,
    fallback: 'blocking',
  }
}

export const getStaticProps: GetStaticProps = async ({ params }) => {
  const query = `
  *[_type=='post' && slug.current == $slug][0]{
    _id,
    publishedAt,
    title,
    description,
    mainImage,
    gallery[0]->{
      title,
      link,
      images,
      display,
    },
    slug,
    body
  }`
  const post = await sanityClient.fetch(query, { slug: params?.slug })

  return {
    props: {
      post,
    },
    revalidate: 10,
  }
}

Although I can see the thumbnail of newly added posts on the website immediately after being uploaded to the CMS, complete with correct image and data, clicking on the thumbnail leads me to a 404 error page.

I am hopeful that someone can provide assistance!

Answer №1

If you're facing a quick fix for a dirty front end code, try redeploying your nextjs app. Simply commit a new change to trigger the building and deployment process, allowing you to see updated page data for the slug.

While this may serve as a temporary solution, there likely exists a more solid approach. Consider exploring the concept of 'Incremental Static Regeneration' in NextJS. Even adding revalidate: 10 to the getStaticProps() function doesn't always yield the desired results. Seeking advice from others who have encountered similar issues could prove beneficial.

Answer №2

To ensure that new blog posts in Sanity appear on your production site immediately after they are published, it is recommended to utilize the getServerSideProps method rather than triggering a build every time.

Answer №3

Having encountered a similar issue and attempting to implement incremental static regeneration (ISR) using Next13's pages/api/revalidate, I've determined that it is not supported and the only solution is to initiate a new build.

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

Is it possible to modify CSS properties using Ajax?

I am attempting to dynamically change the background color of a div using AJAX to fetch the user's specified color from the database. Below is the code snippet I am using: $.ajax({type: "POST", data: {id: id}, url: "actions/css.php", success: functio ...

What is the best way to solve the problem of Chrome auto-complete overlapping with labels in Vuetify?

When attempting to make a login form using outlined text fields in Vutify, there is an issue with Chrome autocomplete overlapping the labels. <v-text-field v-model="email" label="e-mail" name="email" outlined prep ...

Effortless gliding towards the left

I am looking to incorporate buttons for smooth horizontal scrolling within my container. Currently, the functionality is in place but I would like to enhance its smoothness. How can I improve the scrolling experience? Should I consider using a different p ...

What is the best way to restore a component's state to its default settings when it receives new props?

I have a Next.js project in development with a custom Layout already set up. I want the header component to reset whenever a new page is navigated to, so that the menu reverts back to its default state. Does anyone know how I can achieve this? import { F ...

Delay with Vue.js v-bind causing form submission to occur before the value is updated

Trying to update a hidden input with a value from a SweetAlert modal, but encountering issues. The following code isn't working as expected - the form submits, but the hidden field's value remains null. HTML: <input type="hidden" name="inpu ...

The implementation of NextAuth JWT with the header Authorization bearer token in Next.js is a

I'm encountering an issue with my node API where it should technically be accepting a cookie, but for some reason it's not able to retrieve it. cookie: __Secure-next-auth.session-token || next-auth.session-token Within my Next JS application, I ...

Customizing response headers in vanilla Node.js

My Node.js setup involves the following flow: Client --> Node.js --> External Rest API The reverse response flow is required. To meet this requirement, I am tasked with capturing response headers from the External Rest API and appending them to Nod ...

The browser displays the jQuery ajax response instead of passing it to the designated callback function

I have a web application that connects to another web service and completes certain tasks for users. Using codeigniter and jQuery, I have organized a controller in codeigniter dedicated to managing ajax requests. The controller executes necessary actions ...

Creating Varied Results Depending on State Values

I'm in the process of developing a quiz system where different selections lead to distinct outcomes, but I'm facing an issue where the output remains the same. What might be causing this problem? As an example, a user chooses between button 1 an ...

The button effortlessly transforms into a sleek email submission form

I have a button that is already styled with basic CSS properties for active and hover states. I would like to add functionality so that when the "Join the Loop" button is clicked, it transforms into a simple email form similar to the one found at Apologie ...

The Ajax Form disappears from the page

After racking my brain for a while, I've come to the conclusion that it's time to seek some assistance. I have work tomorrow and I don't want to spend all night on this. The issue lies in my form which is located inside a modal, here is my ...

Inserting data into a JavaScript database

When attempting to add a new row to a datatable and submit it to a JSP for database insertion, an error is encountered. The error message reads: "You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the r ...

Guide on initiating document-wide events using Jasmine tests in Angular 2/4

As stated in the Angular Testing guidelines, triggering events from tests requires using the triggerEventHandler() method on the debug element. This method accepts the event name and the object. It is effective when adding events with HostListener, such as ...

Is there a way to remotely access and read text files stored on a server using either JavaScript or Ajax from an IIS6.0 Virtual directory?

Is it possible to use JavaScript or Ajax to read the text from a file on a remote machine (from IIS6.0 Virtual directory) and then copy it into a specific folder on the client machine? ...

Error: Google Chrome encountered an unexpected token } that caused a syntax error

I encountered an error that reads: Uncaught SyntaxError: Unexpected token } This error only appears in Chrome, while other browsers like Mozilla and IE do not show it. Here is my script causing the issue: <script type="text/javascript" language="jav ...

Learn how to showcase vertical text in React Native similar to a drawer

Looking for a way to display text vertically in a dynamic manner, where the length of the text can vary. Below are some examples for reference: Example 1 Example 2 <View> <View style={{}}> <View style={{ marginTop: 30, flexDire ...

Reactjs, encountering a hitch in utilizing material UI: Incompatible hook call detected

As a newcomer to React, I decided to incorporate Material UI components into my project. After installing the components locally using npm install and importing them into my project, I encountered an error when trying to run start: Error: Invalid hook call ...

Updating JSON when the color changes in Go.js can be achieved by implementing event listeners and

I've been using Go.js for creating Flow charts and saving the json data into a SQL database. However, I'm facing difficulties in updating the json data. Here is the code snippet: myDiagram.addDiagramListener("ChangedSelection", function (e1) { ...

The "if" statement carries out the identical action each time it is executed

Despite my efforts to toggle the value of the turn variable every time the if statement runs, I keep encountering the same outcome. It appears that turn consistently evaluates as 2. Below is the code snippet in question: $(function() { var turn = 2; ...

Add an array into an object using $set (properties remain unchanged)

I have an object with the following structure: obj: { 1: { 'a': [ [] ], 'b': [ [] ] } } Now, I am attempting to append 'c' => [ [] ] to this object in a watcher. My first attempt was using this.obj[1][&apo ...