NextJS for Gatsby - Build phases
Coming from Gatsby to NextJS it can be a bit confusing to understand the flow of how pages are generated.
Sometimes the confusion comes in trying to compare the two frameworks as apples and apples, where there are some significant differences.
To clarify -
- Gatsby is a static site generator - you feed data and React components in, plain HTML (and everything else that goes with it) is output ready to be served from any host that serves static HTML files
- NextJS is a platform for building dynamic websites
Where the confusion comes from is that NextJS actually gives you the option to generate static websites. Using NextJS like this brings the two more into alignment, but it does take away a lot of features that make NextJS a more fully-featured platform for building web applications.
Running NextJS projects (that aren't exported as static sites) requires a server running the project. There are hosting providers that abstract this away from you - such as Vercel and Netlify, but you are also able to host the projects yourself.
Back to the topic of this post, the phases of how content is built and output for consumption by browsers differ between the two frameworks.
With Gatsby when you want to publish a new version of the content, the following things occur (some may be abstracted from you through hosting providers).
yarn run gatsby build(or the npm equivalent) is run in the root of your project
- The build output folder is deployed to its hosting location, such as AWS S3, Azure Blob storage, or similar
- Some process occurs to point users visiting your site at the static host
NextJS starts in a similar fashion, but branches off quite drastically.
yarn run next buildis run in the root of the project
- NextJS generates the static version of all pages that either have no dynamic content, or expose a
getStaticPropsfunction, as well as any additional resources needed for running the application
- The whole project can be packaged up for deployment to a server capable of runnning NodeJS applications
- In the root of that package on the server
yarn run next startis executed
- The NextJS server starts listening for incoming requests
- Some process occurs to point users visiting your site at the server
Where NextJS differs is that all the content that is generated at build time can be dynamically re-built while the server is running, so a build and deployment isn't necessary for each content change.
This process is called Incremental Static Regeneration, you can read about it in the NextJS docs.
There are obvious benefits to this, but it introduces some clearly significant issues and concerns -
- The requirement of a server adds a point of attack for malicious users
- Load times could increase, though the use of stale-while-revalidate generally mitigates this