January 29, 2023

Blog @ Munaf Sheikh

Latest news from tech-feeds around the world.

Render anything statically with Next.js and the Megaparam | by Eric Burel


Earlier this year, I’ve published an article about how you can render almost anything statically, at build-time, using Next.js. My goal is to promote “Rainbow Rendering”, the ability to statically render multiple variations of the same page. If you want your home page in seven different possible colors depending on the user’s mood, you can!

The Unicorn of Rainbow Rendering: an architecture to statically render anything, now made possible thanks to Next.js middlewares

Middlewares let you process the request before returning a page. Most common use case is authenticating the user, and redirecting toward a login page if needed.

  • the user hits “/my-page” in their browser.
  • it will show the dark version of my-page, rendered at build-time using getStaticProps . The actual rendered page is “/dark/my-page”, but the URL stays “/my-page” in the browser.

But what happens if in addition to the theme, you also want to setup multi-tenancy or A/B testing?

export async function getStaticPaths() {  
return {
paths: [
{params:{ theme: "dark", tenant: "ACME", bucket: "A"}},
{params:{ theme: "dark", tenant: "ACME", bucket: "B"}},
{params:{ theme: "light", tenant: "ACME", bucket: "A"}},
{params:{ theme: "light", tenant: "ACME", bucket: "B"}},
]
}
}
Resurrecting dead memes is my favorite leisure activity

Who said you add to have one param per param? After all, this parameter won’t be visible to the end user. So you can do as you wish.

  • Using an encoding: “M”==”lXYZB”. First letter is the theme, “l” for “light”, “d” for “dark”. Letters 2 to 4 are the company id in our database, so “XYZ” for “ACME”. Letter 5 is the AB testing bucket, “B”.
  • Binary: “M”==”01111”. You can compute it using any existing encoding/decoding algorithm, based on the possible values for your params.

Because a good code sample says 1000 words, checkout our implementation in Vulcan Next:

  • a file named “megaparam-demo.tsx”, that’s your page
  • in a folder named “[M]”: that’s our Megaparam!
A demo of the Megaparam pattern, used to statically render 4 variations of the same page depending on the theme and user’s company (multi-tenancy)



Source link