happykit / flags

⛳️ Feature Flags for Next.js
https://happykit.dev
MIT License
1.03k stars 11 forks source link

Moving getFlags to Next middleware? #21

Closed richardantao closed 2 years ago

richardantao commented 2 years ago

With the release of Next 12 and Next middleware, there are a ton of new possibilities that are now available to developers. One of the possibilities is being able to run reusable server side code while enabling page caching, which previously wasn't possible with getServerSideProps.

Is it possible to use getFlags inside middleware instead of getServerSideProps? And if not, is it possible for that to be in a future release?

I've currently moved all of my server side logic out of getServerSideProps into middleware, but the only things holding my reliance on getServerSideProps is getFlags from this library.

dferber90 commented 2 years ago

It's exciting that you're trying this! Let me know if you notice anything odd!

This is possible by using getEdgeFlags instead of getFlags. Make sure you're on the latest version :)

You can import it from import { getEdgeFlags } from "@happykit/flags/edge";

Demo and example implementation

Note that you need to use a flags.config.js as described in the migration guide https://github.com/happykit/flags/releases/tag/v2.0.0

One gotcha: Since middleware can't pass props to the page (yet), you can't initialise the client with the servers props like you can with getFlags in getServerSideProps. This is a Next.js limitation at the moment. You an partially work around that by using rewrites and having multiple pages you as shown in the example linked above.

dferber90 commented 2 years ago

I updated the middleware example today to show how to combine getStaticPaths, getStaticProps and middleware to generate the sites statically that the middleware links to. This makes it easier that creating those pages manually, although both works!

https://github.com/happykit/flags/commit/e64b9881e1275050d078128f207a9eddeaab55e3

I’ll close this issue now, as the functionality you requested exists. Happy to reopen if something comes up!

richardantao commented 2 years ago

Awesome, thanks for your help and prompt response Dominik!