Skip to content

Mixing static and dynamic data through layout (for i18n, multi-tenancy...) #44712

Closed

Description

@eric-burel

Describe the feature you'd like to request

Imagine the page structure as follow:

  • Root layout
  • [lang]
  • |___ home page
  • |___ [userId]
  • |_______profile page

The home page has no user-specific data requirements. It is therefore possible to render it statically. Example : it loads a list of articles.
The profile page has user-specific data requirements. It is not possible to render it statically, dynamic rendering per-request is appropriate. Example : data about the current user.
The application also has global, static data requirements. This is the important part. Example: it can load a translation file for global elements ; the name of the company in a multi-tenant architecture ; a layout structure in a backend-driven architecture...

Let's use i18n as an example, eventhough this feature apply to all "segmented" use cases: A/B test, multi-tenant, personalization and friends.

My feature sums up this way:

  • I want to render the home page statically for multiple languages
  • I want to render the profile page dynamically per-request
  • I want the layout to handle the common data requirements

Describe the solution you'd like

Using generateStaticParams in a layout should still allow the children pages to be dynamic.
The layout would handle common, static data requirements, the dynamic pages would handle request-specific data requirements. Static pages can coexist peacefully with the dynamic pages too.

Related:

Describe alternatives you've considered

0) Repro of my current setup with an additional empty generateStaticParams to build dynamic pages

See this codesandbox: https://codesandbox.io/p/sandbox/mix-static-and-dynamic-djho81

You will find an additional generateStaticParams in [lang]/[userId], needed to build, but it is unexpected.

I am experiencing another issue, hydration doesn't work in the built version of this example for unknown reason. I suspect that every time I access a different user id, eg "/fr/42", a new chunk is created in .next for the user, therefore using on-demand rendering (~ISR) instead of dynamic which I want (SSR).

1) Remove generateStaticParams from the layout. Instead, set them in the home page and all static pages.
Problems:

  • it defeats the purpose of the layout, as I must reproduce data requirements in each static page
  • the locales will bloat each static page bundle
  • for dynamic pages, it will refetches the locales

This architecture is similar to how you would handle i18n in Next 12. It lead to issues at Devographics for the State of surveys, because each page bundle would be very fat, leading to slow page transitions.
We moved back to client-side fetching.

2) Use HTTP cache for the static pages
Problems:

  • HTTP caching is more limited than static rendering as you can't control it much at application level. Example: it's harder to support i18n without an explicite lang parameter

3) Make dynamic pages use ISR
The sheer presence of a dynamic route param that is not present in the list returned by generateStaticParams will raise an issue. Therefore it's possible to setup ISR with a dummy generateStaticParams in the dynamic page that returns an empty array.

  • This works but will obviously bloat the system for many requests.

4) cache per request?

The idea would be to use a dynamic render but try to cache everything to make it as fast as possible. This basically means making each "fetch" call "static", instead of using "generateStaticParams" explicitely. I haven't tested so not sure that works.
Anyway this loses the advantages of static rendering, the 1st request will still be expensive.

5) Just use dynamic rendering as soon as one page is dynamic

Say we have 50k users visiting 10 pages on average:

  • the layout chunk will be download 50k, once per user (unless they hard refresh, hard navigate etc.) => that's ok
  • the dynamic pages data are computed 500k times and served 500k times => that's ok
  • the layout data are computed 50k times server-side, so we get 50k db calls => that's bad, a static layout should compute its chunk only 1 time during build

By setting up relevant caches everywhere, it can become acceptable by lowering the actual number of server/db requests, but the whole point of static rendering is too avoid doing that in the first place.

Each approach is probably worth a minimal reproduction, I will try to work on that if it can help but it may take me some time.

Activity

  1. alex-ketch commented on Jan 10, 2023

    @alex-ketch

    Completely agree that a more robust handling of global level static data would be appreciated.

    I also encountered similar hurdles adding i18n to a recent project, but was able to work around it somewhat using the dynamic = 'force static' constant.

    force-static: Force static rendering and static data fetching of a layout or page by forcing cookies(), headers() and useSearchParams() to return empty values.

    Wanted to bring attention to this as a potential alternative.

  2. eric-burel commented on Jan 10, 2023

    @eric-burel
    ContributorAuthor

    Completely agree that a more robust handling of global level static data would be appreciated.

    I also encountered similar hurdles adding i18n to a recent project, but was able to work around it somewhat using the dynamic = 'force static' constant.

    force-static: Force static rendering and static data fetching of a layout or page by forcing cookies(), headers() and useSearchParams() to return empty values.

    Wanted to bring attention to this as a potential alternative.

    And what's the consequence for dynamic pages? Will they still dynamically render after that? I'll try that asap thanks for the idea

    Edit: @alex-ketch this will give me an error like so if I use force-static in the root layout and some nested dynamic page: error - Error: A required parameter (responseId) was not provided as a string in generateStaticParams for /[lang]/survey/[slug]/[year]/[responseId]/[sectionNumber]

    In my simplified example, it means the "userId" param has to be defined during rendering. So force-static doesn't seem to be compatible with having a dynamic parameter, it probably only works for a dynamic page that use no specific parameter.

    For instance this would work:
    Root layout
    [lang]
    |___ home page
    |___ some dynamic page => force-static can render it with empty cookies

    This doesn't:

    Root layout
    [lang]
    |___ home page
    |___ [userId] => doesn't work with force-static, userId has to exist during the static render
    |_______profile page

    Unless I am missing something

  3. changed the title [-]Mixing static and dynamic data through layout[/-] [+]Mixing static and dynamic data through layout (for i18n, multi-tenancy...)[/+] on Jan 11, 2023
  4. sebmarkbage commented on Jan 11, 2023

    @sebmarkbage
    Contributor

    Just to be clear, you're talking about app/ right, where the method is called generateStaticParams (not getStaticParams).

    It just seems like this comment is surfacing a bug to me: #41980 (comment)

    It should be possible to have generateStaticParams in a parent layout without having all children provide a static form.

    However, the solution you mention, should also work:

    export async function generateStaticParams() {
      return [];
    }
    

    It should just be implied, which is a bug.

    This is just saying that the "params" are statically known, not that the pages that they render have to be fully static. If you use cookies() or something that makes them dynamic, each page will still be dynamic. Even if it's not an empty array, but a set of ids that you want to prerender.

    That lets us prerender part of the page (e.g. the head) even if most of the rest of it is still dynamic.

    So is there another issue that you hit when you try that?

  5. eric-burel commented on Jan 11, 2023

    @eric-burel
    ContributorAuthor

    @sebmarkbage I am still in the process of migrating to app folder (and learning) so I couldn't run full experiments on my current app, but to me it feels like generateStaticParams with an empty array will trigger ISR with an infinite timeout, so each dynamically rendered page will be cached instead of being just rendered.

    The doc says that it lists params that will "statically generated at build time instead of on-demand at request time". To me "on-demand" rendering is static rendering on first request, not dynamic rendering, unless I've missed the point.
    https://beta.nextjs.org/docs/api-reference/generate-static-params

    I fixed the function name :)

  6. alex-ketch commented on Jan 11, 2023

    @alex-ketch

    This is just saying that the "params" are statically known, not that the pages that they render have to be fully static. If you use cookies() or something that makes them dynamic, each page will still be dynamic. Even if it's not an empty array, but a set of ids that you want to prerender.

    The issue I was encountering might've been tangential, but was due to using:

    • app/
    • dynamic route segments [[...slug]]
    • and cookies()

    The above raises an error stating Error: Dynamic server usage: cookies
    force-static was my solution to it.

  7. OtisTemler commented on Jan 12, 2023

    @OtisTemler

    Facing the same issue here... Error: A required parameter (orderID) was not provided
    [lang] -> order -> [orderID]

    export async function generateStaticParams() { return []; }
    Fixes it obviously, but that's not ideal.

    Not sure if related but using generateStaticParams for multi-lang in the root layout also results in a broken cookies() and broken headers() Error: Dynamic server usage:
    Not nice if you require the cookies / headers object server side anywhere in the app.

    The same goes for <suspense> or loading.tsx pages => #43350 they don't work as soon as you've generateStaticParams in your root layout that you need for multi-lang use. :)

  8. eric-burel commented on Jan 13, 2023

    @eric-burel
    ContributorAuthor

    I've built a repro on Codesandbox: https://codesandbox.io/p/sandbox/mix-static-and-dynamic-djho81

    Sadly I am hitting an unrelated weird hydration issue, despite using only server components.

    But you can see the architecture. When you build the code, "[lang]/[userId]" is treated as a static file.

    Codesandbox doesn't let me see the content of ".next" so I'll need to try to build locally to finally confirm whether a new chunk is created for each request user (so on-demand behaviour, which is different from dynamic rendering), which I strongly suspect.

  9. sebmarkbage commented on Jan 13, 2023

    @sebmarkbage
    Contributor

    I wonder if #44787 fixes it or if this is a separate issue.

  10. OtisTemler commented on Jan 14, 2023

    @OtisTemler

    Just tested... For me, at least, it doesn't.... :/

  11. eric-burel commented on Jan 20, 2023

    @eric-burel
    ContributorAuthor

    Update, I've crafted a minimal reproduction eventually: https://github.com/eric-burel/nextjs13-mix-dynamic-static
    Check "src/app/[lang]/[userId]/page.tsx" namely
    It's tested against v13.1.3-canary.5

    With generateStaticParams in layout

    • using generateStaticParams = () => [], as I suspected, will trigger on-demand rendering (= ISR). A new page will be built for each user connecting to the app
      image

    • Fix app ISR handling with no generateStaticParams #44787 doesn't seem to have any effect on this issue (cc @ijjk), if I had "export dynamic = "force-dynamic" I still have the initial error:

    • force-static fails with the same error but directly during build

    Here is what the code can look like for the dynamic page:

    // As is, this code will produce: "Error: A required parameter (userId) was not provided as a string in generateStaticParams for /[lang]/[userId]"
    
    // Option 1: will trigger ISR = 1 page is stored per user, not what we want
    // export const generateStaticParams = () => [];
    
    // Option 2: explicit our intent to use dynamic rendering, doesn't work, same error
    // export const dynamic = "force-dynamic";
    
    export default function UserProfile({ params }: any) {
      console.log("Rerendering user profile page");
      return (
        <div>
          <p>Params from UserProfile: {JSON.stringify(params)}</p>
          <Link href={`${params.lang}`}>Back to home</Link>
        </div>
      );
    }

    If I remove generateStaticParams in layout

    • it works again with no change in the "userId" page BUT the userId page still uses on-demand rendering and will produce 1 page per userId requested!

    • By adding an explicit "export const dynamic = "force-dynamic"", I finally ge the behaviour I want

    Summary

    In layout In userId page result
    generateStaticParams fr and de nothing error, userId param is missing
    generateStaticParams fr and de generateStaticParams with empty array userId uses on-demand rendering (bad)
    generateStaticParams fr and de force-dynamic error, userId param is missing
    nothing nothing userId uses on-demand rendering (bad)
    nothing dynamic="force-dynamic" finally works, but the home page uses on-demand rendering, not static rendering

    Finding the right combination is not obvious and I can't prerender my home in multiple languages. I can add generateStaticParams back to the home page, but that means having to repeat the list of languages everywhere.

    I think I can now rephrase the expected behaviour more clearly:

    Current solution

    Root layout
    [lang] -> nothing
    |___ home page -> define generateStaticParams for lang (have to be done for all pages)
    |___ [userId]
    |_______profile page -> uses dynamic rendering

    It's similar to how things would be done in v12 but it's hard to figure and defeat the purpose of layouts a bit. The layout seems to behave as expected though, it won't rerender the "french" layout multiple time during navigation between home and profile for instance, which is cool.

    Expected behaviour

    Root layout
    [lang] -> layout defines generateStaticParams
    |___ home page -> uses generateStaticParams from layout implicitly
    |___ [userId]
    |_______profile page -> if dynamic, ignore generateStaticParams from layout

    Using "generateStaticParams" in a layout should implicitly behave as defining this same "generateStaticParams" function in all children pages except for pages is using/forcing dynamic rendering, in which case it should be ignored.
    Ambiguous cases could still throw an error to avoid mistakes, eg if I forget to tell that "userId" is dynamic and it doesn't use headers/cookies.

  12. eric-burel commented on Nov 22, 2023

    @eric-burel
    ContributorAuthor

    Small up on this: I think Partial Prerendering could solve this issue?
    If we can have dynamic components within static pages, we can maybe have dynamic pages within static layouts? Anything would prevent that? Perhaps it will even work out-of-the-box in Next 14.1 with PPR?

  13. locked and limited conversation to collaborators on Apr 17, 2024
  14. converted this issue into a discussion #64616 on Apr 17, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions