#Using generateStaticParams with on-demand ISR

1 messages · Page 1 of 1 (latest)

wraith sandalBOT
#

Hi @lucid birch. I'm kapa.ai, your friendly support bot. I will try to answer your question by searching through the knowledge base. :wave:

#

Yes, you can use generateStaticParams in combination with on-demand Incremental Static Regeneration (ISR) in Next.js. Here’s how you can achieve this:

  1. Define generateStaticParams: This function will be used to statically generate the initial set of pages at build time.

  2. Set up ISR: You can configure ISR to revalidate the pages at a specified interval or on-demand.

Here’s an example of how you can set this up:

// app/blog/[slug]/page.js

// Return a list of `params` to populate the [slug] dynamic segment
export async function generateStaticParams() {
  const posts = await fetch('<https://.../posts'>).then((res) => res.json())
 
  return posts.map((post) => ({
    slug: post.slug,
  }))
}
 
// Multiple versions of this page will be statically generated
// using the `params` returned by `generateStaticParams`
export default function Page({ params }) {
  const { slug } = params
  // ...
}

In this example, generateStaticParams fetches a list of posts and returns the slugs to statically generate the pages at build time.

To enable ISR, you can set the revalidate property in your page component:

export const revalidate = 60; // Revalidate the page every 60 seconds

For on-demand ISR, you can use API routes to trigger revalidation:

// pages/api/revalidate.js

export default async function handler(req, res) {
  // Check for secret to confirm this is a valid request
  if (req.query.secret !== process.env.MY_SECRET_TOKEN) {
    return res.status(401).json({ message: 'Invalid token' })
  }

  try {
    // Revalidate the specific path
    await res.revalidate('/blog/[slug]')
    return res.json({ revalidated: true })
  } catch (err) {
    return res.status(500).json({ message: 'Error revalidating' })
  }
}
#

Key Points:

  • Static Generation: generateStaticParams is used to statically generate pages at build time.
  • ISR: You can set a revalidation interval using the revalidate property or trigger revalidation on-demand using API routes.

For more details, you can refer to the Next.js documentation on generateStaticParams (https://nextjs.org/docs/app/api-reference/functions/generate-static-params) and ISR (https://nextjs.org/docs/basic-features/data-fetching/incremental-static-regeneration).

If you need further assistance, please let me know!

Note: you can ask me a follow up question by @ mentioning me again :speech_balloon:

#

@lucid birch kapa.ai is still learning and improving, please let us know how it did by reacting below

lucid birch
wraith sandalBOT
#

Let me check the knowledge base for you. One moment! :books:

#

Sorry @lucid birch, I seem to be having a bit of trouble. Don't worry though, I've pinged my support and they will try to fix me up! :technologist:

Perhaps try again in 15mins?

lucid birch
#

@wraith sandal import getCurrentUser from '@/app/actions/getCurrentUser';
import ClientOnly from '@/app/components/ClientOnly';
import EmptyState from '@/app/components/EmptyState';
import EventCategoryRegion from './EventCategoryRegion';
import { Metadata } from 'next';
import { generateCategoryRegionPaths } from '@/app/utils/generatePaths';
import getEventsByCategoryAndRegion from '@/app/actions/getEventsByCategoryAndRegion';

interface IParams {
category?: string;
region?: string;
}

export async function generateStaticParams() {
const paths = generateCategoryRegionPaths();
return paths.map((path) => ({
category: path.category,
region: path.region,
}));
}

const EventCategoryRegionPage = async ({ params }: { params: IParams }) => {
try {
const currentUser = await getCurrentUser();

const { category, region } = params;

const events = await getEventsByCategoryAndRegion(category, region);

if (!events || events.length === 0) {
  return <EmptyState />;
}

return (
  <ClientOnly>
    <EventCategoryRegion
      events={events}
      currentUser={currentUser}
      category={category}
      region={region}
    />
  </ClientOnly>
);

} catch (error) {
console.error(error);
return <EmptyState />;
}
};

export default EventCategoryRegionPage;
Is this correct way of usage? 'use server';

import { revalidatePath } from 'next/cache';

export default async function revalidateEvents() {
revalidatePath('/events/category/[category]/[region]');
}

wraith sandalBOT
#

Let me check the knowledge base for you. One moment! :books:

#

Based on the provided code and the knowledge sources, your usage of generateStaticParams and the server-side logic looks mostly correct. However, there are a few points to consider for clarity and correctness:

  1. generateStaticParams Function: This function is correctly used to generate static paths for the dynamic routes.

  2. Server-Side Component: The EventCategoryRegionPage component is correctly fetching data on the server side.

  3. Revalidation: The revalidateEvents function is set up to revalidate the path for on-demand ISR.

Here’s a refined version of your code with some minor adjustments for clarity:

import getCurrentUser from '@/app/actions/getCurrentUser';
import ClientOnly from '@/app/components/ClientOnly';
import EmptyState from '@/app/components/EmptyState';
import EventCategoryRegion from './EventCategoryRegion';
import { Metadata } from 'next';
import { generateCategoryRegionPaths } from '@/app/utils/generatePaths';
import getEventsByCategoryAndRegion from '@/app/actions/getEventsByCategoryAndRegion';

interface IParams {
  category?: string;
  region?: string;
}

export async function generateStaticParams() {
  const paths = generateCategoryRegionPaths();
  return paths.map((path) => ({
    category: path.category,
    region: path.region,
  }));
}

const EventCategoryRegionPage = async ({ params }: { params: IParams }) => {
  try {
    const currentUser = await getCurrentUser();
    const { category, region } = params;
    const events = await getEventsByCategoryAndRegion(category, region);

    if (!events || events.length === 0) {
      return <EmptyState />;
    }
#

return (
<ClientOnly>
<EventCategoryRegion
events={events}
currentUser={currentUser}
category={category}
region={region}
/>
</ClientOnly>
);
} catch (error) {
console.error(error);
return <EmptyState />;
}
};

export default EventCategoryRegionPage;


For the revalidation function:

```javascript
import { revalidatePath } from 'next/cache';

export default async function revalidateEvents() {
  revalidatePath('/events/category/[category]/[region]');
}

Key Points:

  • Static Generation: generateStaticParams is used to statically generate pages at build time.
  • Server-Side Rendering: The EventCategoryRegionPage component fetches data on the server side.
  • On-Demand ISR: The revalidateEvents function triggers revalidation for the specified path.

For more details, you can refer to the Next.js documentation on generateStaticParams (https://nextjs.org/docs/app/api-reference/functions/generate-static-params) and ISR (https://nextjs.org/docs/basic-features/data-fetching/incremental-static-regeneration).

If you need further assistance, please let me know!

Note: you can ask me a follow up question by @ mentioning me again :speech_balloon: