josias
josias

Reputation: 1626

Next.js: Codesplitting for conditional wrapper

I'm a Next.js newbie.

I was wondering, how I can achieve the following:

My goal is to create some kind of back-end / admin-area for existing pages. My idea is to create an auth wrapper inside _app.js that will always check whether there is an auth token stored in local storage. If so, if not, the accessed page would simply be displayed. Otherwise, on successful authentication, I want to inject some editing capabilities.

Now I'm worried about performance issues. Since React will get bundled, won't all the editing capabilities get bundled into the code? Even tho they won't be used by usual users and is only thought for admins.

That would be a problem for me when the component gets very large since most users will download that code, which they would never touch.

I know that Next.js has code-splitting out of the box, but the way I understood it, Next.js will split the code per-page, and since the editor component would get injected for every page, it would be there for every page, wouldn't it?

So basically, how can I split the editor component into a single file, that would only get downloaded when the auth component' condition returns true?

I read about React.lazy(), but I'm not sure if that is meant for such use cases. Also, I'm curious, how I could do the same with just React and not just Next.js if the same concept applies.

I appreciate all the help!

Upvotes: 0

Views: 265

Answers (1)

josias
josias

Reputation: 1626

Okay, after some tinkering I think I found the solution myself.

First I tried using React.lazy(), but that isn't yet supported by Next.js (it's not supported by ReactDOMServer to be precise).

So I found the dynamic method from Next.js, which seems to be doing the same thing. I've created a simple wrapper that will set a condition to true after some seconds and was able to observe the network request to the dynamically loaded component appear after those seconds, which means it worked. 🥳

Still, I've not much experience with this. If anyone finds a preferred way to do this, please let me know!

Upvotes: 1

Related Questions