> For AI agents: the complete documentation index is available at /llms.txt, the full documentation bundle is available at /llms-full.txt.

# Static Site Generation

SSG (Static Site Generation) is a technical solution that generates complete static web pages at build time based on data and templates. This means that in a production environment, pages are pre-rendered with content and can be cached by a CDN. SSG can offer better performance and higher security for pages that do not require dynamic data.

## Enabling SSG

To enable SSG functionality in a Modern.js project, follow these steps to modify the code:

1. Install SSG plugin dependencies

If the SSG plugin is not yet installed in your project, install it first:

```bash
pnpm add @modern-js/plugin-ssg
```

:::tip Version Consistency

Make sure the version of `@modern-js/plugin-ssg` matches the version of `@modern-js/app-tools` in your project. All Modern.js official packages are released with a uniform version number, and version mismatches may cause compatibility issues.

Check the version of `@modern-js/app-tools` first, then install the same version of `@modern-js/plugin-ssg`:

```bash
# Check the current version of @modern-js/app-tools
pnpm list @modern-js/app-tools

# Install the same version of @modern-js/plugin-ssg
pnpm add @modern-js/plugin-ssg@<version>
```

:::

2. Configure modern.config.ts

Import and add the SSG plugin in the `modern.config.ts` file, and configure `output.ssg`:

```ts title="modern.config.ts"
import { defineConfig, appTools } from '@modern-js/app-tools';
import { ssgPlugin } from '@modern-js/plugin-ssg';

export default defineConfig({
  plugins: [appTools(), ssgPlugin()],
  output: {
    ssg: true,
  },
});
```

:::info Scope of Application

- Use `output.ssg` for single-entry apps.
- Use `output.ssgByEntries` for multi-entry apps.
- When only `output.ssg: true` is set and `output.ssgByEntries` is not configured, all routes under all entries will be treated as SSG routes.

:::

## Development Debugging

Since SSG also renders pages in a Node.js environment, we can enable SSR during the **development phase** to expose code issues early and validate the SSG rendering effect:

```ts title="modern.config.ts"
export default defineConfig({
  server: {
    ssr: process.env.NODE_ENV === 'development',
  }
}
```

## Using SSG in Conventional Routing

In **conventional routing**, Modern.js generates routes based on the file structure under the entry point, allowing the framework to collect complete route information.

### Basic Usage

For example, the following is a project directory structure using conventional routing:

```bash
.
└── routes
    ├── layout.tsx
    ├── page.tsx
    └── user
        ├── layout.tsx
        ├── page.tsx
        └── profile
            └── page.tsx
```

The above file directory will generate the following three routes:

- `/`
- `/user`
- `/user/profile`

:::tip
If you are not familiar with the rules of conventional routing, refer to the [Routing Solution](/guides/basic-features/routes/routes.md) first.

:::

Add component code in `src/routes/page.tsx`:

```jsx title="src/routes/page.tsx"
export default () => {
  return <div>Index Page</div>;
};
```

Run the command `pnpm run dev` at the project root and check the `dist/` directory, where only one HTML file `main/index.html` is generated.

Run the command `pnpm run build` at the project root, and after the build completes, check the `dist/` directory again. This time, you'll find `main/index.html`, `main/user/index.html`, and `main/user/profile/index.html` files, each corresponding to the routes listed above.

Each route in **conventional routing** will generate a separate HTML file. Checking `main/index.html`, you will find it contains the text `Index Page`, which demonstrates the effect of SSG.

After running `pnpm run serve` to start the project, inspect the returned document in the Network tab of the browser's development tools. The document includes the fully rendered content from the component.

## Using SSG in Manual Routing

**Manual routing** defines routes through component code, requiring the application to run to obtain accurate route information. Therefore, you cannot use the SSG feature out of the box. Developers need to configure which routes require SSG.

For example, consider the following code with multiple routes. By setting `output.ssg` to `true`, it will only render the entry route (`/`) by default.

```tsx title="src/App.tsx"
import { BrowserRouter, Route, Routes } from '@modern-js/runtime/router';
import { StaticRouter } from '@modern-js/runtime/router/server';
import { use } from 'react';
import { RuntimeContext } from '@modern-js/runtime';

const Router = typeof window === 'undefined' ? StaticRouter : BrowserRouter;

export default () => {
  const context = use(RuntimeContext);
  const pathname = context?.request?.pathname;
  return (
    <Router location={pathname}>
      <Routes>
        <Route index element={<div>index</div>} />
        <Route path="about" element={<div>about</div>} />
      </Routes>
    </Router>
  );
};
```

If you want to enable SSG for `/about` as well, you can configure `output.ssg`:

```ts title="modern.config.ts"
export default defineConfig({
  output: {
    ssg: {
      routes: ['/', '/about'],
    },
  },
});
```

After running `pnpm run build`, you will see a new `main/about/index.html` file in the `dist/` directory.

After running `pnpm run serve` to start the project, inspect the returned document in the Network tab of the browser's development tools. The document includes the fully rendered content from the component.

:::info
The above example introduces single-entry scenarios. For more information, refer to the [API Documentation](/configure/app/output/ssg.md).
:::

## Adding Dynamic Routes

For manual routing, provide concrete paths directly in `routes`. You can also use this configuration for conventional routing with dynamic segments (for example, `/user/[id]`).

```js
export default defineConfig({
  output: {
    ssg: {
      routes: ['/', '/about', '/user/modernjs'],
    },
  },
});
```

### Generating Parameters Alongside a Loader

For file-system conventional routing, export `ssgParams` from the page's `page.data.ts` to generate paths from route parameters. Enable SSG to use this convention. Generator discovery does not apply to config routes.

Use an explicit named export or re-export, such as `export { ssgParams } from './params'`. Exports available only through `export *` are not discovered.

For example, `src/routes/blog/[slug]/page.data.ts` can share the published-post selection logic with its loader:


```ts title="src/routes/blog/[slug]/page.data.ts"
import type { SSGParams } from '@modern-js/plugin-ssg'
import { getPublishedPosts } from '@/data/posts'

export const ssgParams: SSGParams = async () => {
  const posts = await getPublishedPosts()
  return posts.map(post => ({ slug: post.slug }))
}

export const loader = async ({ params }: { params: { slug: string } }) => {
  const posts = await getPublishedPosts()
  const post = posts.find(post => post.slug === params.slug)
  if (!post) {
    throw new Response('Not Found', { status: 404 })
  }
  return post
}
```

If the published posts have the slugs `hello` and `getting-started`, Modern.js generates `/blog/hello` and `/blog/getting-started`. With `routes` omitted or empty, it also prerenders the entry's non-dynamic routes. The loader still reads data for one page and runs during prerendering. Its return value is not used to enumerate paths.

`ssgParams` takes no arguments and returns an array of parameter objects, synchronously or asynchronously. It runs once per page route during the SSG build, in Node.js using the application's server compilation. It can use path aliases and server dependencies such as filesystem access. SSG uses the existing server data-loader boundary to keep the generator and its server dependencies out of browser bundles. When debugging code that imports Node.js dependencies, [enable SSR during development](#development-debugging). The function is not called by `dev` or `serve`.

#### Parameter Values

Each path segment can contain ASCII letters, digits, `-`, `.`, `_`, or `~`. Empty segments, `.`, and `..` are rejected. A slug such as `release.v3` generates an `index.html` inside that page's directory.

| Route file                               | Parameter object                    | Generated path                 |
| ---------------------------------------- | ----------------------------------- | ------------------------------ |
| `routes/[lang]/blog/[slug]/page.data.ts` | `{ lang: 'en', slug: 'hello' }`     | `/en/blog/hello`               |
| `routes/blog/[slug$]/page.data.ts`       | `{}`                                | `/blog`                        |
| `routes/blog/[slug$]/page.data.ts`       | `{ slug: 'hello' }`                 | `/blog/hello`                  |
| `routes/docs/$.data.ts`                  | `{ '*': 'guides/getting-started' }` | `/docs/guides/getting-started` |

For nested routes, each object must include all required parent and child parameters. Parameters are not collected or combined from `layout.data.ts`. Omit an optional parameter or set it to `undefined` to omit that segment. For a wildcard page (`$.tsx`), export `ssgParams` from `$.data.ts` and use the `'*'` key. Use `/` between segments of a wildcard value.

An empty array adds no paths for that page. You can still list a path for it explicitly in `routes`. Duplicate generated paths are rendered once. Dynamic routes without `ssgParams` remain excluded from automatic SSG.

A missing required parameter, a non-string value other than `undefined` for an optional parameter, an invalid result, or an exception fails the build with a route-specific error.

#### Combining Explicit and Generated Paths

A non-empty `output.ssg.routes` list is combined with the paths returned by `ssgParams`. For example, with `routes: ['/about']` and the blog generator above, Modern.js prerenders `/about`, `/blog/hello`, and `/blog/getting-started`. Other non-dynamic paths are included only if explicitly listed or returned by a generator.

When both sources produce the same URL, Modern.js renders it once with the explicit route's options, including its `headers` and `output`. Omitting `routes` or setting `routes: []` also includes non-dynamic routes automatically. The same rules apply to `output.ssgByEntries`. Disabling SSG for an entry also disables its generators.

## SSG Matching for Parent and Child Routes

For a blog, `src/routes/blog/page.tsx` renders the list and `src/routes/blog/[slug]/page.tsx` renders an article. After enabling SSG, you can prerender both the list and selected articles:


```ts title="modern.config.ts"
export default defineConfig({
  output: {
    ssg: {
      routes: ['/blog', '/blog/hello'],
    },
  },
})
```

Each path generates its own static HTML. The built-in production server matches SSG pages by their exact paths:

| Request path           | Behavior                                                        |
| ---------------------- | --------------------------------------------------------------- |
| `/blog`                | Returns the static HTML for the blog list                       |
| `/blog/hello`          | Returns the static HTML for the article                         |
| `/blog/does-not-exist` | Does not match an SSG page and falls back to an available entry |

Requests to a trailing-slash URL such as `/blog/` receive an HTTP 308 redirect to `/blog`, preserving the query string. For example, `/blog/?preview=1` redirects to `/blog?preview=1`.

The SSG page at `/blog` does not act as a fallback for `/blog/*`. Defining a `[slug]` route does not automatically generate static HTML for every slug. List concrete paths in `routes`, generate them with `ssgParams`, or combine both.

This example does not enable SSR or prerender the root entry `/`. An unmatched path therefore receives the root entry's CSR shell, and routing continues in the browser. The initial HTML response is typically HTTP 200. An unknown slug alone does not cause the server to return 404.

If a matching SSR entry exists, SSR determines the response content and status. If no entry matches, the server returns 404. If you also configure the root entry `/` for SSG, it only matches its own path and no longer provides a wildcard fallback.

## Handling 404 Responses During Prerendering

Continuing the example, suppose you add `/blog/scheduled` to `output.ssg.routes`, but the article has not been published yet. Its loader can throw a 404 during the build. Here, `getPost` is your application's article lookup function, and `publishedAt` is the publication timestamp in milliseconds:


```ts title="src/routes/blog/[slug]/page.data.ts"
import { getPost } from '@/data/posts'

export const loader = async ({ params }: { params: { slug: string } }) => {
  const post = await getPost(params.slug)
  if (!post || post.publishedAt > Date.now()) {
    throw new Response('Not Found', { status: 404 })
  }
  return post
}
```

When prerendering returns 404 or another non-2xx response, the build:

- Logs a warning containing the path and status code.
- Skips the page's static HTML file and SSG route registration.
- Continues generating pages with successful responses.

The error page is therefore not saved as static HTML that would later be served with HTTP 200. Requests to `/blog/scheduled` follow the entry fallback rules above. The build-time 404 is not stored as the path's runtime response status.

SSG only generates pages during a build. Reaching the publication time does not automatically generate the missing static HTML. Rebuild and redeploy to generate the article's SSG page.

## Multi-entry

For multi-entry apps, configure per entry via `output.ssgByEntries`:

```js
export default defineConfig({
  output: {
    ssgByEntries: {
      home: {
        routes: ['/', '/about', '/user/modernjs'],
      },
      admin: false,
    },
  },
});
```

:::info
See API details: [output.ssgByEntries](/configure/app/output/ssgByEntries.md)
:::

## Configuring Request Headers for Rendering

Modern.js supports configuring request headers for specific entries or routes. For example:

```js
export default defineConfig({
  output: {
    ssg: {
      headers: {
        'x-tt-env': 'ppe_modernjs',
      },
      routes: [
        '/',
        {
          url: '/about',
          headers: {
            from: 'modern-website',
          },
        },
      ],
    },
  },
});
```

In the above configuration, the `x-tt-env` request header is set for all routes, and the `from` request header is specifically set for the `/about` route.

:::tip
Headers set in routes will override headers set for entries.
:::
