Next.js Discord

Discord Forum

Fetch data from CMS in a component (not a page) server-side

Answered
Asian black bear posted this in #help-forum
Open in Discord
Asian black bearOP
Hi folks πŸ‘‹
We are using Storyblok as headless CMS and the Next.js 14 Page Router and SSG. For now we use [...slug].tsx, getting the pages in getStaticPaths() and passing the slug to getStaticProps(), then fetching this specific data for this slug from the CMS. For pages, this works good.
But what if we have a component which has to fetch data. For example, we have a TeamOverview component which needs to get all team members. We want to be able to dynamically use this component on all pages (inserting the component in the CMS). Since this is a component and not a page, we cannot use getStaticProps() in there. Everyone is telling us to use useEffect(), but is this really the best practice? Discarding all high-performance features like SSG/SSR and fetch everything client-side, just because it's a component and not a page?
Answered by joulev
this is where the app router shines: you effectively have getStaticProps for all components in the app router.

if you need to use the pages router, you probably have to use a prebuild script in lieu of getStaticProps: https://github.com/joulev/debug/tree/nextjs-pages-router-global-static-data-example
View full answer

4 Replies

Answer
Asian black bearOP
so you mean with useContext?
@Asian black bear so you mean with useContext?
not necessarily context. what i meant is that you make a json file during the build process and simply import that json file. how you propagate the data (by contexts for example) is up to you.
Asian black bearOP
okay, thanks