zdenham / next-static-utils

Tooling to host Next.js websites with app router statically
12 stars 0 forks source link

⚡️ Next Static Utils ⚡️
Utilities to host your next.js app as a static site wherever your heart desires
Including dynamic routes and app router support

Example

Check out the example repo and the live demo site.

Motivation

Next.js offers an option for static site generation, which allows you to export your site as raw html, js, etc... and host it statically on a CDN, or however you like! This reduces the infra overhead of your application, if you are willing to sacrifice SSR features.

But SSG does not work with dynamic routes unless you generate all pages at build time. There are some discussions around this issue here and here, which the Vercel team will hopefully resolve soon. But even so, most static hosting providers outside of Vercel don't know how to handle the way next.js does code splitting out of the box, which can lead to unwanted 404 errors.

Next Static Utils aims to provide workarounds and utilities to address some of these issues and make hosting your next.js site statically anywhere you darn well please a bit more enjoyable.

Starting with support for AWS S3 + Cloudfront, but can presumably add other providers relatively easily.

Set Up

Installation And CLI

pnpm install next-static-utils
...
# Generates edge function for re-routing to a fallback page for dynamic params
pnpm next-static-utils generate [cloudfront|serve]

Usage

On your dynamic page:

import { withDynamicParams } from 'next-static-utils';

// creates fallback parameter page
export const generateStaticParams = withDynamicParams();

To use the dynamic paramaters:

'use client';

import { useDynamicParams } from 'next-statis-utils';

export default function Component() {
  // pulls params from the url, e.g. /users/:id
  const { id } = useDynamicParams();

  return (
    <div>
      Hello
    </div>
  )
}

Recommended Next Config

export default (phase) => {
  const nextConfig = {
    output: phase === 'phase-production-build' ? 'export' : 'standalone',
  };
  return nextConfig;
};

Who its for

Private / auth gated applications, admin dashboards, simple tools, blogs & content sites with a relatively small catalog can all work.

How it works

For every dynamic route, next static utils generates a fallback page which is served for dynamic routes, this also satisfies next.js's requirement to generate static params when using the output: export option.

Instead of using useParams which is not supported in SSG mode, the params are provided with a new hook useDynamicParams

The CLI also generates a cloudfront function to properly handle re-routing at an edge function level in AWS.

Other Cool / Related Projects

TODO