Is it achievable to dynamically generate new pages on initial load in NextJS?

Right now, I am utilizing getStaticProps and getStaticPaths to pre-render a specific number of articles before my website goes live. This method works effectively, but if a new article is created and displayed on the front page while the site is still active, the new article ends up displaying a 404 error page.

What I really want is for non-existent pages to pass their id (such as mysite.com/posts/id in the /posts/[id].js file) to a function that would allow the page to be dynamically pre-rendered on the server during runtime. I do not wish to resort to using getServerSideProps, since that would mean rendering the page with each request. Instead, I am seeking a way to permanently render the page and save it as an SEO-friendly file similar to how getStaticProps operates, but within the runtime environment.

In simpler terms, I am searching for a behavior similar to getStaticPaths/getStaticProps but applicable during runtime in NextJS.

If this is not achievable, I am wondering how I can ensure that newly created articles are readily accessible without needing to intermittently bring down the server, rebuild it, and restart it - a process that appears quite unmanageable.

Answer №1

TL:DR Is it possible to achieve getStaticPaths/getStaticProps behavior during runtime in NextJS?

It's a bit of a yes and no situation. There is a revalidate option available, but currently, it requires a client-side request to invalidate outdated data and then fetch updated data. This may result in User A seeing old data while User B sees the updated data. Unfortunately, there isn't a way to automatically trigger a revalidation upon CRUD events.

One workaround, although not recommended, is to manually initiate a client-side request after a CRUD event to ensure both users see the most recent data. However, this approach can lead to longer response times for CRUD operations.

At present, using getServerSideProps is the only reliable method to ensure 100% up-to-date data for SEO purposes. If SEO indexing is not a concern, client-side requests should suffice.

Answer №2

After some exploration, I discovered a simple solution that had eluded me. In the getStaticPaths function, all you need to do is set fallback: true. Then, within the function component, add some temporary fallback content for viewers to see while the server renders the new page and sends it back. For example, in [id].js:

export default function Post({ postProps}) {
    const router = useRouter()
    
    if (router.isFallback) {
        return <div>Loading...</div>
    }

    return (
        ...
    )
}

By following this approach, the server can utilize getStaticProps on the new ID to render the fresh page, while the client sees "Loading..." temporarily. Once the rendering process is complete, the client is presented with the updated page. This rendering only needs to occur once for new pages and will be easily accessible for subsequent views or SEO crawlers.

reference

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

Rotate image in Vue3 using @click

I have a dashboard with a refresh button that I want to rotate 360 degrees every time it is clicked. How can I achieve this rotation effect on the image with each click of the refresh button? Below is the code snippet I have been working on, but it only r ...

Enhance Material UI with custom properties

Is it possible to add custom props to a Material UI component? I am looking to include additional props beyond what is provided by the API for a specific component. For example, when using Link: https://material-ui.com/api/link/ According to the document ...

Remix is throwing a Hydration Error while trying to process data mapping

While working on my Remix project locally, I encountered a React hydration error. One thing I noticed is that the HTML rendered by the server does not match the HTML generated by the client. This issue seems to be related to the Material UI library usage. ...

ReactJS import duplication problem arising from utilizing npm link for component testing prior to npm package release

I have a basic component structured like this. import React, {useState} from 'react'; function MyComponentWithState(props) { const [value, setValue] = useState(0); return ( <p>My value is: {value}</p> ) } expo ...

Exploring the wonders of Jasmine coding with jQuery

I am relatively new to conducting Jasmine tests. I have a basic understanding of how to install it and use simple commands like toEqual, toBe, etc. However, I am unsure of how to write test code for this particular jQuery function using Jasmine. if ($(&ap ...

Using jQuery, you can easily insert a <span> tag around selected text and then save this modification permanently in a local HTML file

I have compiled notes in an HTML file stored on my local computer, with the intention of keeping it solely for personal use. For instance, I have a snippet like this: <p> this is an example text</p> My goal is to highlight the word "example" ...

AJAX allows developers to declare variables within their code to

Here is a snippet of my JavaScript code: $(\"img.agree\").click(function() { var follow_id = $(this).attr(\"id\"); var user_id = $(\"img.user_id\").attr(\"id\"); $.ajax({ type: \"POST& ...

Oops! Looks like there's a hiccup with the express-validator plugin as the validation fails due to req.checkBody not being recognized as

Currently, I am setting up a post route to handle a submit request. The code snippet provided is from my user.js route: var express = require('express'); var router = express.Router(); var multer = require('multer'); var upload = multe ...

Is it possible to transfer data from javascript to php through ajax?

I am attempting to extract the data speedMbps from my JavaScript code using Ajax to send the data to my PHP script, but unfortunately, I am not receiving any output. My experience with Ajax is limited to implementing auto-completion feature. <script sr ...

What's causing my struggle to override the bootstrap nav-link class in next.js?

I am facing an issue where I need to customize the active state of bootstrap .nav-link in the code snippet below: <li className="nav-item"> <a className={`${styles.navLink} nav-link`} role="tab" data-to ...

There is no Api.js file in the Cordova iOS platform

I have been attempting to integrate the iOS platform into a new Cordova 7.0.1 project, but I continuously encounter the error mentioned in the title of this post. Despite following the steps outlined in this thread here, including removing and re-adding ...

Increment and decrement the like count on fa-heart multiple times

Is there a way to increment the count of a fa-heart value on click and decrement it on the second click? The issue I'm facing is that I have multiple fa-heart elements on the same page, making it challenging to increment or decrement the clicked fa-h ...

Calculate the number of parent nodes and their respective child nodes

I am curious about how I can determine the number of children nested within parent-child relationships. For example: const parent = document.querySelectorAll('.parent'); parent.forEach(el => { const ul = el.querySelector('.child3-chi ...

Seeking help with executing JQuery Ajax functions within a foreach loop

Currently, I am engrossed in the study of programming and endeavoring to construct a website utilizing .Net Core. The predicament at hand pertains to my limited acquaintance with JavaScript while incorporating two JQuery/AJAX functions on my Index page - o ...

Unable to add or publish text in CKEditor

In my ASP.NET MVC application, I am struggling to post the updated value from a CKEditor in a textarea. Here is the code snippet: <textarea name="Description" id="Description" rows="10" cols="80"> This is my textarea to be replaced with CKEditor ...

Enhancing Typography in Material UI with Custom Breakpoints in React CustomThemes

Currently, I am utilizing material UI and React to develop a single-page application (SPA). However, I have encountered an issue with ensuring that my pages are responsive for smaller screen sizes. To address this, I have been manually adding fontSize: { x ...

Node.js and Express facing challenge with Stripe checkout functionality

I am encountering an issue while attempting to integrate stripe into my checkout process. When I click on the checkout button, instead of being directed to the checkout page, I receive the following message: {"url":"https://checkout.stripe.c ...

Entry Points for Logging In

After stumbling upon this pre-styled Material UI login page example, I decided that it was exactly what I needed. However, I ran into an issue when trying to figure out how to store the username and password values. Whenever I try to use 'State' ...

Issue with ng-checked not detecting boolean values retrieved from local storage

I'm working on a code snippet in my controller where I have a checkbox in my HTML with "ng-checked="enterToSend" and "ng-click="enterToSendCheck()" attached to it. $scope.enterToSend = localStorage.getItem('enterToSend'); $scope.enterToSen ...

React JS tutorial: deleting an entry from the browser's localStorage

I am currently working on an App that fetches data from an API and updates it randomly every 3 seconds. The user has the ability to print the data by clicking a button, which can also be used to stop the random updates. I have managed to implement this fun ...