Use getStaticProps and getServerSideProps together #11424
Replies: 31 comments 79 replies
-
It might help if you give a specific example - I can't really thing of any usecase, except if you might actually have data on the server which must necessarily be send alongside your rendered page somehow instead of doing a simple client-side fetch(Is that what you`re looking for?). For the actual performance benefit of serving a static page, the whole approach certainly imposes the constraint that your data on the server which I guess you want to fetch in If you have additional data available on the server which you want to use, expose it over an api endpoint and fetch that on the client. In theory there might actually be a possible approach where you could stitch together a big part of static page data with a small portion that relies on dynamic data into one page - But besides the added complexity making this approach prone to a lot of errors, a full static page can always be served faster (and more performant), leaving enough time then on the client to fetch additional data once it recieved the instruction to do that from a script in that server response. Getting back to the initial theory, where you send server data alongside your page, the issue here would proably be that in nearly all cases, the static html data is available sooner than your server function could execute, meaning that waiting for the function to complete would result in an additional delay. That's how I understood things so far, but I stand corrected. |
Beta Was this translation helpful? Give feedback.
-
I am in need of the ability to execute some middleware on the server to restrict access to static content. The ability to use
|
Beta Was this translation helpful? Give feedback.
-
For me there is value in build time data fetching with runtime rendering.
…On Wed, Jun 3, 2020, 8:35 AM Raffaele ***@***.***> wrote:
Not really, the page could be dynamically generated from the server as it
needs to load dynamic data per-request but, for static content only, it
will use also the result of getStaticProps which will be loaded once at
build-time and reused every time the page is requested.
In the end, the page component will get data from both getStaticProps(loaded
once at build time) and getServerProps (loaded on every request) as props.
—
You are receiving this because you commented.
Reply to this email directly, view it on GitHub
<#11424 (reply in thread)>,
or unsubscribe
<https://github.com/notifications/unsubscribe-auth/AAWY34IPWJFUEFKHJT22NEDRUZNR7ANCNFSM4LVP62VA>
.
|
Beta Was this translation helpful? Give feedback.
-
Hello, using nextjs 10 it seems we have the same issue (here with prisma and meilisearch as a usecase but can be very common). What can we do about this ? If it's not possible, is there a suggested workaround ? |
Beta Was this translation helpful? Give feedback.
-
I have same request. FYI this is the one issue preventing me from hosting on Vercel, if I can't figure out an alternative solution. My use case: Paywalled publication. The pages are all static and the core content is fully known at build time. But for reasons of paywall integrity, it's important that no content hits the client computer unless the auth cookie is first inspected and approved server side. What I'd like to do is have getStaticProps generate all the content at build time, so it's ready to quickly serve after authentication, and then getServerSideProps only has to inspect the auth cookie. But right now I have to choose between the two. If the page uses getStaticProps, I can't authenticate server side before the content gets delivered to the client. If I understand the docs correctly, it seems the official solution (https://nextjs.org/docs/authentication#authenticating-statically-generated-pages) is to use client side JS to fetch the gated content after authenticating. But for my use case, most of the content is gated. It's not just eg a username and some dashboard numbers. So I lose the whole point of an SSG framework. Likewise, I could use getServerSideProps for the whole page, but again, then I don't get any static site generation benefits. Other than combining getStaticProps and getServerSideProps on the same page, an alternative solution would be if I could check cookies in some route/middleware script. That way I could intercept unauthenticated users before they got served the gated content. I believe there's been talk of this feature as well. Is there some other NextJS / Vercel solution for this use case I'm not aware of? Or is it just fundamentally impossible to combine server side authentication with SSG content? I'm also looking at a Cloudflare Workers solution, where I would use some vanilla SSG (NextJS or otherwise), upload the resulting static assets to Workers KV, and then use a Worker to inspect the cookie at request time before serving the static content. |
Beta Was this translation helpful? Give feedback.
-
I have another use case that has a similar bottleneck. We have a catalogue of 30 product categories, in 5 languages, in 30 different countries with various stock and currency availability, which I believe quite a typical example of a mid size e-commerce shop. The issue is that there are 4500 possible permutations of |
Beta Was this translation helpful? Give feedback.
-
I have a use case that need to list post details Static and to show comments from Server Side as they keep updating. |
Beta Was this translation helpful? Give feedback.
-
I would like to build a form layout based on a sequel ORM model and then populate the form on every page request. This feels like an elegant way to keep both the ORM model and HTML form layout in sync. |
Beta Was this translation helpful? Give feedback.
-
There are a lot of arguments against this feature, but it seems logical to me that if there is an argument for So either It could be that |
Beta Was this translation helpful? Give feedback.
-
I mean, to be honest it is a use case that must be supported if you want any kind of widespread adoption. getStaticProps and getStaticPaths + getStaticProps are mighty fine when the paths are known at compile time and are a reasonable number. If you are working on a 8 language e-commerce with 400 thousand products per sub-site where content needs to be either statically generated or computed at server time (my current use case), you are going to want to use server side rendering. Right now I'm in the situation where product and category listings are computed using getServerSideProps, everything else is done via getStaticProps (possibly in combination with getStaticPaths), and stuff which we are computing at compile time (and later revalidating via ISR) for every page via getStaticProps, is instead computed via getServerSideProps in pages that are generated at runtime, making them significantly slower than they actually need to be (and hitting more API endpoints than they need to, way more often than they must). |
Beta Was this translation helpful? Give feedback.
-
I think overhauling getStaticProps/getServerSideProps to incorporate this would be a nightmare. Plus it would mess up all the pretty documentation. I'd just be happy with some lifecycle/middleware functions to use to allow one last server side shot to make a decision....especially where it concerns authentication and redirects. Essentially ALL pages are server side rendered, it's just that the static ones are pre rendered. It still has to make the roundtrip to the server to retrieve what's already there. A beforeSSR and afterSSR would be mighty helpful in doing minor checks and balances, logging, redirecting or flat out cancelling the request and possibly saving on some gnarly SSR logic. Any content managed by a CDN is a completely different architecture and even that has authorization at the edge for the major cloud services. Lifecycle hooks would also help discourage abuse of overloading business logic or long running tasks that are not asynced. That's what getServerSideProps is for. |
Beta Was this translation helpful? Give feedback.
-
This could be done in a straight forward way. Basically, For In this way, the queries that don't change even with query params could still be cached, and only new queries that change based on query params (like pagination) would be run in SSR. Seems like that'd be very manageable. |
Beta Was this translation helpful? Give feedback.
-
I think @bendman described my situation and how I found this discussion the best:
I have a site where I want parts of the data fetching to be dynamic and up-to-date (not just the "the next visitor will get up-to-date data" functionality that To describe my specific example, it's this site: ath.ooo. Every crypto asset ticker symbol has a page, e.g. ath.ooo/BTC. So my data fetching has to start by pulling a list of all crypto assets in CoinGecko's database so it can map between ticker symbols and the unique IDs CoinGecko uses for each asset (since ticker symbols can overlap). So the other requests I have to make in But overall I know data fetching stuff is pretty complicated, and maybe what I'm describing is something that just doesn't fit within the paradigm or abstraction that the Next team has created. (If anyone has suggestions for my specific situation I'm all ears.) |
Beta Was this translation helpful? Give feedback.
-
I think I might have a more simple example of why this is necessary. I have a report page that has both static and dynamic content. The static content is stuff that I would like to pull from my internalization library. The dynamic content is data for a report page. I'd love to be able to render the report localized to the current user while still feeding them the data they requested. Per the Next docs recommendation, we're using Of course, our report is rendered client side the first time it's loaded through a next/link but users can reload the report directly. At that point, we don't want to have to build a loader for that use case and just want to render the content in place which would require Without the ability to use both methods for data fetch, I have to get creative with the legacy |
Beta Was this translation helpful? Give feedback.
-
Another problem we are currently facing - and please enlighten me if there already is another, better approach - is that we are building an intranet that lives behind a Single-Sign On which provides a cookie including a JWT token. This token can easily be verified using Since the intranet obviously contains a lot of data, our desired solution would have been to get all data such as news on build using static site generation and authenticate the user server-side on demand, which currently is not possible, since unfortunately |
Beta Was this translation helpful? Give feedback.
-
Another use case: using Right now, I'm running into a
To dig into the example, you can also imagine restaurant menu data which never changes so |
Beta Was this translation helpful? Give feedback.
-
This is very useful and is needed by us too.
Can this be done currently ? |
Beta Was this translation helpful? Give feedback.
-
A simple use case for this... We have a blog on our site that is generated with markdown files. The markdown parsing should obviously happen in However, the blog has a header that is shared across all pages which shows a user avatar when you are signed in and a sign in button when you are not. We fetch the auth info in So, we need a special header for the blog that doesn't contain any auth info or "sign in" button, because we can't show already signed in users a "sign in" button |
Beta Was this translation helpful? Give feedback.
-
I ended up forking the repository and adding a new component static function called 'beforeGetProps' that is called on every request in renderToResponseWithComponent in next-server.ts. It acts more like a lifecycle event so as to not mangle up the standard next workflow. It was surprisingly trivial. The build process doesn't run through the same path so it doesn't creep in when building the static pages. The function allows 3 different returns; Redirect, Not Found, RenderServerSide (where renderServerSide is a function that acts as an adhoc getServerSideProps). This allowed us to have static pages while solving the following problems:
I know this doesn't solve all cases stated in this post but could be helpful for those with issues like we've had above. Some folks have mentioned dynamic data that needs to be injected into SRR pages but that seems like an anti-pattern and it's not something that React even handles in their SSR offerings. Since Next is basically just caching the result of Reacts SSR functions I don't think it's feasible to get both dynamic and static when requesting a page from the server. You either SSR and return the entire app, as is, or you don't. Maybe there's some smart people working on that but, in the meantime, SSR isn't replacing the fact that you have a client side application running and that you'll have to add client side logic for that dynamic data, inevitably dealing with a loading indicator. For Next Contributors: As for the separation of getStaticProps and getServerSideProps, It seems counterproductive. Since every request is inevitably checking and forking based on which one is present it doesn't make any sense to have these split. These functions can be merged under one and just pass a param letting the developer know where in the process it's coming from (build process vs dev server vs prod server) and then allow us to serve up the cached page vs a new SSR by simply noting that in the props returned. That gives the developer much more freedom to determine how the system behaves. |
Beta Was this translation helpful? Give feedback.
-
Does version 12 introduce anything that could help achieve this? I'm thinking about Edge functions or React Server Components (alpha) somehow |
Beta Was this translation helpful? Give feedback.
-
We would love to have this as well. |
Beta Was this translation helpful? Give feedback.
-
Hi everyone! Just want to let you all know that this is something we are thinking about and discussing on the next team. I appreciate all the constructive conversation here and apologize for the slow response. Will get more updates in here as soon as I have them 😁 |
Beta Was this translation helpful? Give feedback.
-
One more use case here: You have an above the fold A/B test with content coming from your CMS. You have all the variants at build time, but assign the variant at runtime. In this way, you're fetching from the CMS only once but able to do the assignment an unlimited amount of times. In my mind, this would require forwarding the props from |
Beta Was this translation helpful? Give feedback.
-
Hopefully we can get an update for this. Right now, by using automatic static optimization, I can't use authentication with my page, which is a big hindrance that forces me to ignore the feature for now. |
Beta Was this translation helpful? Give feedback.
-
I also have a use case, one that doesn't involve authentication. I have a directory of static items (GSP) and these are sortable by category options at the top of the page. Clicking one of the options updates the state via useEffect and refilters the data yada yada. There is one main link to the directory and the default state is set to 'All', but I'd like to have specific links that only display the matching category of the data on load.
From my understanding, the way to do it would be GSP accesses the directory items and GSSP would access the query param and set the category state on load. However, I'm new to next and still learning react in general, so if there's another way to accomplish this, I'm all ears. |
Beta Was this translation helpful? Give feedback.
-
Hi all, sharing my solution: |
Beta Was this translation helpful? Give feedback.
-
Hi @jescalan, is there any update on if/when this might be available? |
Beta Was this translation helpful? Give feedback.
-
Can this be achieved with the new data fetching pattern introduced in Next 13? |
Beta Was this translation helpful? Give feedback.
-
Update: We’re excited to announce Next.js 13, which includes the new Inside the You can leave feedback here: #41745 |
Beta Was this translation helpful? Give feedback.
-
With the stable App Router in 13.4, static or dynamic data can be fetched, cached, and used together in the same route segments.
export default async function Page() {
const static = await fetch('https://...');
const dynamic = await fetch('https://...', { cache: 'no-store' });
return '...';
} |
Beta Was this translation helpful? Give feedback.
-
As far as I understood the new data fetching strategies
getStaticProps
andgetServerSideProps
introduced with the RFC #9524 are mutually exclusive but I believe there are many cases where we could enjoy the benefits of both of these approaches.Let's say I want to build a page where most of the content is static and could be loaded at build-time, but there is a small portion of data that must be loaded at request-time and for SEO reasons the whole page must be rendered server-side. This could be the case of a homepage of multilanguage e-commerces or marketplaces where most of the content is static and could be fetched at build-time based on a provided language but the "featured product" section must always be loaded with the most updated content per request.
Right now the only solutions I can think of to keep TTFB low and avoid fetching static content on each request are:
Fetch static content at build-time running a customized script which will save data in a JSON file, which will be load later in
getServerSideProps
together with dynamic content or imported as a moduleFetch both static and dynamic content in
getServerSideProps
and use a custom cache layer to cache only static content for future requests.Both solutions force developers to write custom caching logic and/or DevOps strategies to build and deploy this kind of application, while it could be easier if we could just use
getStaticProps
andgetServerSideProps
together. In this scenario, static content could be loaded at build-time usinggetStaticProps
while dynamic content used for server-side rendering will be loaded per-request usinggetServerSideProps
. In the case, we are not enjoying the full benefits of SSG pages but we can still reduce TTFB by loading static content only once at build-time.What do you think about this solution? Could it be a new proposal for an RFC? Are there any other solutions I haven't considered?
Beta Was this translation helpful? Give feedback.
All reactions