Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to properly implement serverless SSR with Next.js using `target: "serverless"` in version 8.0

Next.js 8.0 just introduced a new target: "serverless" config setting, described on this blog post. I set up a basic hello world app (here) to test it out. Copy-pasted the output of .next/serverless/pages/index.js to a Google Cloud Function (their equivalent of AWS Lambda) and had it call render() as outlined in the above blog post.

The problem I run into is that the page itself renders fine, but then it tries to fetch static assets (script files) at the same domain as the lambda, which of course doesn't work because there's nothing there but the lambda script.

You can see this happening here: enter image description here

The idea I was going for was to use this new feature of Next.js to implement a micro-frontend architecture. Each page in pages/ could have its own development team / lifecycle, and be scaled accordingly on the backend. That is one of the main selling points of this feature, right?

What is the standard way of solving this? Do I need to set up a separate server for the static assets? Then put both behind a load balancer or router of some sort? If so, doesn't that defeat the purpose of using this to develop micro-frontends, since the static assets would include "index.js", "about.js", and script files for each page, and would need to be redeployed any time any page is updated?

Hope what I'm saying makes sense. Any help appreciated!

like image 509
NateQ Avatar asked Sep 06 '25 05:09

NateQ


1 Answers

Do I need to set up a separate server for the static assets?

I'm new nextjs, but yes, I believe that is what you need.

Since you are on GCP, you might want to try Firebase because it includes the Google Cloud Functions (a FB Function is a Google Cloud Function just packaged and marketed separately) and static hosting that takes care of your requirement including the details you mentioned.

The one other issue is that this new serverless feature of nextjs seems a little more oriented towards AWS Lambda in that it packages the functions seperately. You are probably already aware but I will note anyway that GCP is 'project' oriented and all the functions in your project share a single entry point. I won't go into any more detail since it is not what you question is about, but this popular SO question goes into how to do that.

edit: I wrote that and then remembered this FB sample... a different way to host a nextjs app on Firebase based on an older version of nextjs.

like image 110
Tom Avatar answered Sep 08 '25 00:09

Tom