Next.js Discord

Discord Forum

Generate all blogs at build time

Answered
Devon Rex posted this in #help-forum
Open in Discord
Devon RexOP
Hello everyone, lets say I have a function to get all of my blogs called
getBlogs()
How can I fetch all of my blogs, and render them all out on build time instead of when the user navigates to /blog/[slug]. I know I will need the [slug] folder, but with that the user navigates and then it builds it. How can I get them prebuilt at build time, and then any invalid slugs will return a 404. I am on Next 14.1.0
Answered by Black Caiman
Mhm so refactor the generateStaticParams to pass in a list of service slugs and then in the page function (btw you should captitalize components in general), make it async and then you need to do something like const service = await getServiceFromSlug(params.service). Then you can use the object.
View full answer

5 Replies

Plott Hound
@Plott Hound You need to use generateStaticParams https://nextjs.org/docs/app/api-reference/functions/generate-static-params
Devon RexOP
export async function generateStaticParams() {
    const { services } = await getServices();

    return services?.map((service: any) => ({
        service: service,
    }));
}

export default function page({ params }: any) {
    console.log(params);
    return <div>tes</div>;
}


Logging the params only prints out the current URL I am on and doesnt print my object. Am I doing something wrong with it?
Devon RexOP
I see, you return the slug to prebuild all of your existing pages. I got it figured out now
Black Caiman
Mhm so refactor the generateStaticParams to pass in a list of service slugs and then in the page function (btw you should captitalize components in general), make it async and then you need to do something like const service = await getServiceFromSlug(params.service). Then you can use the object.
Answer