# Vite SSR HTML
> 使用原生 HTML、Vite 和 Nitro 实现服务器端渲染。
```html [index.html]
Nitro Quotes
Powered by
Vite
and
Nitro v3.
```
```json [package.json]
{
"type": "module",
"scripts": {
"build": "vite build",
"dev": "vite dev",
"preview": "vite preview"
},
"devDependencies": {
"@tailwindcss/vite": "^4.1.18",
"nitro": "latest",
"tailwindcss": "^4.1.18",
"vite": "beta"
}
}
```
```json [tsconfig.json]
{
"extends": "nitro/tsconfig"
}
```
```ts [vite.config.ts]
import { defineConfig } from "vite";
import { nitro } from "nitro/vite";
import tailwindcss from "@tailwindcss/vite";
export default defineConfig({
plugins: [
nitro({
serverDir: "./",
}),
tailwindcss(),
],
});
```
```ts [app/entry-server.ts]
import { fetch } from "nitro";
export default {
async fetch() {
const quote = (await fetch("/quote").then((res) => res.json())) as {
text: string;
};
return tokenizedStream(quote.text, 50);
},
};
function tokenizedStream(text: string, delay: number): ReadableStream {
const tokens = text.split(" ");
return new ReadableStream({
start(controller) {
let index = 0;
function push() {
if (index < tokens.length) {
const word = tokens[index++] + (index < tokens.length ? " " : "");
controller.enqueue(new TextEncoder().encode(word));
setTimeout(push, delay);
} else {
controller.close();
}
}
push();
},
});
}
```
```ts [routes/quote.ts]
const QUOTES_URL =
"https://github.com/JamesFT/Database-Quotes-JSON/raw/refs/heads/master/quotes.json";
let _quotes: Promise | undefined;
function getQuotes() {
return (_quotes ??= fetch(QUOTES_URL).then((res) => res.json())) as Promise<
{ quoteText: string; quoteAuthor: string }[]
>;
}
export default async function quotesHandler() {
const quotes = await getQuotes();
const randomQuote = quotes[Math.floor(Math.random() * quotes.length)];
return Response.json({
text: randomQuote.quoteText,
author: randomQuote.quoteAuthor,
});
}
```
该示例演示了如何渲染带有服务器端数据的 HTML 模板,并逐字流式传输响应内容。它展示了如何在不使用框架的情况下,利用 Nitro 的 Vite SSR 集成。
## 概览
#### **添加 Nitro Vite 插件** 以启用 SSR
#### **创建一个 HTML 模板**,在服务器内容插入处添加 `` 注释
#### **创建一个服务器入口**,获取数据并返回一个流
#### **添加用于服务器端数据的 API 路由**
## 工作原理
`index.html` 文件包含一个 `` 注释,标记服务器渲染内容将被插入的位置。Nitro 会用你的服务器入口输出替换该注释。
服务器入口导出一个带有 `fetch` 方法的对象。它使用 Nitro 的内部 fetch 调用 `/quote` API 路由,然后返回一个 `ReadableStream`,该流以每个单词间隔 50ms 的速度逐字发送引用文本。
引用路由从 GitHub 获取包含多个引用的 JSON 文件,缓存结果,并返回一个随机引用。服务器入口调用此路由以获取页面内容。
## 了解更多
- [Renderer](/docs/renderer)
- [Server Entry](/docs/server-entry)