+
Skip to content

feat(vite-plugin-nitro): add support for conditional server rendering at runtime #1623

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 6 commits into from
Feb 25, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 12 additions & 2 deletions apps/analog-app/vite.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

import analog from '@analogjs/platform';
import { visualizer } from 'rollup-plugin-visualizer';
import { defineConfig, Plugin, splitVendorChunkPlugin } from 'vite';
import { defineConfig, Plugin } from 'vite';
import { nxViteTsPaths } from '@nx/vite/plugins/nx-tsconfig-paths.plugin';
import inspect from 'vite-plugin-inspect';

Expand Down Expand Up @@ -33,7 +33,7 @@ export default defineConfig(({ mode, isSsrBuild }) => {
additionalPagesDirs: ['/libs/shared/feature'],
additionalAPIDirs: ['/libs/shared/feature/src/api'],
prerender: {
routes: ['/', '/cart', '/shipping', '/client'],
routes: ['/', '/cart', '/shipping', '/client', '/404.html'],
sitemap: {
host: base,
},
Expand All @@ -45,6 +45,16 @@ export default defineConfig(({ mode, isSsrBuild }) => {
},
},
liveReload: true,
nitro: {
routeRules: {
'/cart/**': {
ssr: false,
},
'/404.html': {
ssr: false,
},
},
},
}),
nxViteTsPaths(),
visualizer() as Plugin,
Expand Down
32 changes: 31 additions & 1 deletion apps/docs-app/docs/features/server/server-side-rendering.md
Original file line number Diff line number Diff line change
Expand Up @@ -27,9 +27,39 @@ export default defineConfig(({ mode }) => ({

For more information about externals with SSR, check out the [Vite documentation](https://vitejs.dev/guide/ssr.html#ssr-externals).

## Hybrid Rendering with Client-Only Routes

SSR is enabled by default. For a hybrid approach, you can specific some routes to only be rendered client-side, and not be server side rendered. This is done through the `routeRules` configuration object by specifying an `ssr` option.

```ts
import { defineConfig } from 'vite';
import analog from '@analogjs/platform';

// https://vitejs.dev/config/
export default defineConfig(({ mode }) => ({
// ...other config
plugins: [
analog({
prerender: {
routes: ['/', '/404.html'],
},
nitro: {
routeRules: {
// All admin URLs are only rendered on the client
'/admin/**': { ssr: false },

// Render a 404 page as a fallback page
'/404.html': { ssr: false },
},
},
}),
],
}));
```

## Disabling SSR

SSR is enabled by default. You can opt-out of it and generate a client-only build by adding the following option to the `analog()` plugin in your `vite.config.ts`:
You can opt-out of it and generate a client-only build by adding the following option to the `analog()` plugin in your `vite.config.ts`:

```ts
import { defineConfig } from 'vite';
Expand Down
7 changes: 7 additions & 0 deletions apps/docs-app/docs/features/server/static-site-generation.md
Original file line number Diff line number Diff line change
Expand Up @@ -91,8 +91,15 @@ export default defineConfig(({ mode }) => ({
'/about',
'/blog',
'/blog/posts/2023-02-01-my-first-post',
// Prerender 404.html page for SPAs
'/404.html',
],
},
nitro: {
routeRules: {
'/404.html': { ssr: false },
},
},
}),
],
}));
Expand Down
2 changes: 1 addition & 1 deletion libs/card/project.json
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
"projectType": "library",
"tags": [],
"targets": {
"test": {
"tests": {
"executor": "@nx/vite:test"
},
"lint": {
Expand Down
10 changes: 6 additions & 4 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -63,17 +63,19 @@
"@trpc/client": "^10.25.0",
"@trpc/server": "^10.25.0",
"ajv-formats": "^2.1.1",
"defu": "^6.1.4",
"destr": "^2.0.1",
"front-matter": "^4.0.2",
"isomorphic-fetch": "^3.0.0",
"marked": "^5.0.2",
"marked-gfm-heading-id": "^3.1.0",
"marked-highlight": "^2.0.1",
"mermaid": "^10.2.4",
"react": "^18.3.1",
"react-dom": "^18.3.1",
"rxjs": "7.8.1",
"semver": "^7.6.3",
"radix3": "^1.1.1",
"react": "^18.2.0",
"react-dom": "^18.0.0",
"rxjs": "7.8.0",
"semver": "^7.5.1",
"superjson": "^2.2.1",
"tslib": "^2.7.0",
"ufo": "^1.5.4",
Expand Down
2 changes: 1 addition & 1 deletion packages/nx-plugin/src/generators/app/generator.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -226,7 +226,7 @@ describe('nx-plugin generator', () => {
const hasTrpcClientFile = tree.exists('apps/trpc-app/src/trpc-client.ts');
const hasNoteFile = tree.exists('apps/trpc-app/src/note.ts');
const hasTrpcServerRoute = tree.exists(
'apps/trpc-app/src/server/routes/trpc/[trpc].ts',
'apps/trpc-app/src/server/routes/api/trpc/[trpc].ts',
);
expect(hasTrpcClientFile).toBeTruthy();
expect(hasNoteFile).toBeTruthy();
Expand Down
10 changes: 10 additions & 0 deletions packages/platform/src/lib/options.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,16 @@ import type { SitemapConfig } from '@analogjs/vite-plugin-nitro';

import { ContentPluginOptions } from './content-plugin.js';

declare module 'nitropack' {
interface NitroRouteConfig {
ssr?: boolean;
}

interface NitroRouteRules {
ssr?: boolean;
}
}

export interface PrerenderOptions {
/**
* Add additional routes to prerender through crawling page links.
Expand Down
21 changes: 21 additions & 0 deletions packages/platform/src/lib/platform-plugin.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,27 @@ export function platformPlugin(opts: Options = {}): Plugin[] {

let nitroOptions = platformOptions?.nitro;

if (nitroOptions?.routeRules) {
nitroOptions = {
...nitroOptions,
routeRules: Object.keys(nitroOptions.routeRules).reduce(
(config, curr) => {
return {
...config,
[curr]: {
...config[curr],
headers: {
...config[curr].headers,
'x-analog-no-ssr': !config[curr].ssr ? 'true' : undefined,
} as any,
},
};
},
nitroOptions.routeRules,
),
};
}

return [
...viteNitroPlugin(platformOptions, nitroOptions),
...(platformOptions.ssr ? [ssrBuildPlugin(), ...injectHTMLPlugin()] : []),
Expand Down
4 changes: 3 additions & 1 deletion packages/vite-plugin-nitro/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,9 @@
"dependencies": {
"nitropack": "^2.10.0",
"xmlbuilder2": "^3.0.2",
"esbuild": "^0.20.1"
"esbuild": "^0.20.1",
"radix3": "^1.1.1",
"defu": "^6.1.4"
},
"ng-update": {
"packageGroup": [
Expand Down
10 changes: 10 additions & 0 deletions packages/vite-plugin-nitro/src/index.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,14 @@
import { nitro } from './lib/vite-plugin-nitro.js';
export { Options, SitemapConfig } from './lib/options.js';

declare module 'nitropack' {
interface NitroRouteConfig {
ssr?: boolean;
}

interface NitroRouteRules {
ssr?: boolean;
}
}

export default nitro;
39 changes: 29 additions & 10 deletions packages/vite-plugin-nitro/src/lib/plugins/dev-server-plugin.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,11 +11,16 @@ import {
import { resolve } from 'node:path';
import { readFileSync } from 'node:fs';
import { createEvent, sendWebResponse } from 'h3';
import { createRouter as createRadixRouter, toRouteMatcher } from 'radix3';
import { defu } from 'defu';
import { NitroRouteRules } from 'nitropack';

import { registerDevServerMiddleware } from '../utils/register-dev-middleware.js';
import { Options } from '../options.js';

export function devServerPlugin(options: Options): Plugin {
type ServerOptions = Options & { routeRules?: Record<string, any> | undefined };

export function devServerPlugin(options: ServerOptions): Plugin {
const workspaceRoot = options?.workspaceRoot || process.cwd();
const entryServer = options.entryServer || 'src/main.server.ts';
const index = options.index || 'index.html';
Expand Down Expand Up @@ -57,18 +62,32 @@ export function devServerPlugin(options: Options): Plugin {
template,
);

const _routeRulesMatcher = toRouteMatcher(
createRadixRouter({ routes: options.routeRules }),
);
const _getRouteRules = (path: string) =>
defu(
{},
..._routeRulesMatcher.matchAll(path).reverse(),
) as NitroRouteRules;

try {
const entryServer = (
await viteServer.ssrLoadModule('~analog/entry-server')
)['default'];
const result: string | Response = await entryServer(
req.originalUrl,
template,
{
let result: string | Response;
// Check for route rules explicitly disabling prerender
if (
_getRouteRules(req.originalUrl as string).prerender === false ||
_getRouteRules(req.originalUrl as string).ssr === false
) {
result = template;
} else {
const entryServer = (
await viteServer.ssrLoadModule('~analog/entry-server')
)['default'];
result = await entryServer(req.originalUrl, template, {
req,
res,
},
);
});
}

if (result instanceof Response) {
sendWebResponse(createEvent(req, res), result);
Expand Down
10 changes: 8 additions & 2 deletions packages/vite-plugin-nitro/src/lib/runtime/renderer.ts
Original file line number Diff line number Diff line change
@@ -1,14 +1,20 @@
import { eventHandler } from 'h3';

import { eventHandler, getResponseHeader } from 'h3';
// @ts-ignore
import renderer from '#analog/ssr';
// @ts-ignore
import template from '#analog/index';

export default eventHandler(async (event) => {
const noSSR = getResponseHeader(event, 'x-analog-no-ssr');

if (noSSR === 'true') {
return template;
}

const html = await renderer(event.node.req.url, template, {
req: event.node.req,
res: event.node.res,
});

return html;
});
19 changes: 16 additions & 3 deletions packages/vite-plugin-nitro/src/lib/vite-plugin-nitro.ts
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,13 @@ export function nitro(options?: Options, nitroOptions?: NitroConfig): Plugin[] {
let hasAPIDir = false;

return [
(options?.ssr ? devServerPlugin(options) : false) as Plugin,
(options?.ssr
? devServerPlugin({
entryServer: options?.entryServer,
index: options?.index,
routeRules: nitroOptions?.routeRules,
})
: false) as Plugin,
{
name: '@analogjs/vite-plugin-nitro',
async config(userConfig, { mode, command }) {
Expand Down Expand Up @@ -287,18 +293,25 @@ export function nitro(options?: Options, nitroOptions?: NitroConfig): Plugin[] {
* This file is shipped as ESM for Windows support,
* as it won't resolve the renderer.ts file correctly in node.
*/
import { eventHandler } from 'h3';

import { eventHandler, getResponseHeader } from 'h3';
// @ts-ignore
import renderer from '${ssrEntry}';
// @ts-ignore
const template = \`${indexContents}\`;

export default eventHandler(async (event) => {
const noSSR = getResponseHeader(event, 'x-analog-no-ssr');

if (noSSR === 'true') {
return template;
}

const html = await renderer(event.node.req.url, template, {
req: event.node.req,
res: event.node.res,
});

return html;
});
`,
Expand Down
Loading
点击 这是indexloc提供的php浏览器服务,不要输入任何密码和下载