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

Learn how to handle internationalization routing in Next.js by utilizing a slash instead of a dash

I manage a website with multiple countries, each country having more than one locale. Below is the configuration from my next-i18next.config.js: module.exports = { i18n: { defaultLocale: 'en-eg', locales: ['en-br', 'en-eg ...

Tips on slowing down the Jquery UIBlock Plugin

Currently, I am implementing a plugin found at http://jquery.malsup.com/block/#overview. However, I am interested in configuring the blockUI feature to only be displayed if an AJAX request takes longer than 1 second. Otherwise, I would prefer for nothing ...

TypeORM ensures that sensitive information, such as passwords, is never returned from the database when retrieving a user

I developed a REST API using NestJs and TypeORM, focusing on my user entity: @Entity('User') export class User extends BaseEntity { @PrimaryGeneratedColumn() public id: number; @Column({ unique: true }) public username: string; publi ...

How should a successful post request be properly redirected in React?

I am in the process of learning React and currently working on a small project. I have set up a NodeJS server to handle my requests, and now I am facing an issue with redirecting the user after a successful login. I successfully dispatch an action and upda ...

Transform uploaded image file into a blob format and store it in a VueJS database

I am facing an issue with my form that has multiple inputs, including one of type "file". My goal is to upload an image and then submit the form to the API for storage in the database. <input name="image" class="w-full border-2 border-gray-200 rounded-3 ...

Discover the power of Vue.js 3 by seamlessly integrating anonymous functions within event handlers

Is it possible to invoke an anonymous function within an event handler in Vue.js 3? I came across several options on various websites: <button @click="return function() { console.log('test')}()">Click me</button> <butto ...

Automate table column width adjustments in HTML using Selenium WebDriver

As of now, I am working on automating the process of increasing the width of an HTML table column using Selenium WebDriver. I discovered that I can retrieve the coordinates of x and y by using findElement(By.cssSelector("<Css locator>").getLocation( ...

In Vue.js2, you can easily compare two arrays of objects that have the same values and then make changes or add properties from one array to the other

I am working with an array of objects fetched from an API (), which is linked to a variable that serves as the v-model for an input. Whenever the variable changes, so does the array through a function that triggers the API call on @keyup. The structure of ...

What is the correct way to properly enter a Svelte component instance variable?

Currently, I am delving into learning Svelte and specifically exploring how to bind to a component instance as demonstrated in this tutorial: As I progress through the tutorial, I am attempting to convert it to Typescript. However, I have encountered an ...

Automatically unselect the "initially selected item" once two items have been selected in Material UI

As someone new to web development, I'm struggling with a specific task. Here is the issue at hand: I have three checkboxes. If box1 and then box2 are selected, they should be marked. However, if box3 is then selected, box1 should automatically unchec ...

Trouble with Component Lifecycle (ComponentDidMount) activation while switching tabs in TabBar?

After implementing the react-native-tab-navigator library to navigate between components, I encountered an issue where the componentDidMount lifecycle method works only once. I have reached out for help by posting a query on Github and have also attempted ...

Utilizing TypeScript Variables within a Jquery Each Iteration

I have a variable named tableIndexNumber that I need to use in different methods. When trying to access this variable, I use "this.tableIndexNumber" and it works fine. However, I face an issue when using it inside a jQuery each loop because the HTML elemen ...

Tips for refreshing HTML multiple file upload without reloading the page

I am currently working on a feature that involves counting the number of files uploaded. If more than 10 images are uploaded, I want to clear the input field while keeping everything else in the form intact. Everything was working fine until I encountered ...

Choosing the fourth cell in every row of a table and converting the information

Currently, I am working on a function that is supposed to take the fourth column in each row of a specific table, manipulate the data using a function, and return different data for the cell. This function takes an integer representing total minutes as i ...

Using NodeJS to convert a Base64 string into a JPEG image with the help of either NodeJS or

I have successfully stored a JPEG image in my MySQL database using the longblob format. Now, when I retrieve the longblob data, I am only getting a base64 string. How can I convert this base64 string back to a readable JPEG image using MySQL or Node.js? B ...

What could be the reason for Sequelize's findAll() method returning only a single object?

I am currently facing an issue where I can only retrieve one record out of many similar records when searching for products by brand and model name using Sequelize. This problem occurs even if there are multiple matching records, with the additional ones h ...

"Performing a series of getJSON requests with a delay between each call, iterating through an array

Could someone shed light on why my jQuery/JavaScript code runs with an unexpected flurry of ajax calls instead of at a steady 1-per-second rhythm? var i = 0, l = data.length; function geocode() { $.getJSON( 'https://maps.googleapis.com/maps/api ...

Ensure that the execution of the function is completed before moving on to the next iteration within a $.each loop

While I'm not an expert in JS or jQuery, I'm currently working on coding a chat application that requires the following functionality: Retrieve conversation list through an AJAX call Display the conversations on the left side of the webpage aft ...

A specific image is loading after being clicked in a new page

Despite my efforts to search on various platforms, I have not been able to find a comprehensive solution to my query. Scenario: I currently have a webpage containing a div with multiple images. These images load without any issues and are set to open in ...

Size three canvas, woven with triple strands of fiber

I am currently facing an issue with the dimensions of a three-fiber canvas. I require specific fixed width and height for the canvas, but I cannot figure out how to adjust these parameters. Although I've tried changing the sizes using style={{width: 1 ...