Deploying Vite Projects with SSR
How to add SSR to a Vite project to Freestyle
Setup
When you're setting up a Vite project for SSR, use the vite-extra
CLI to give you all the parts you need for SSR.
npm create vite-extra@latest
This will create a Vite project with the extra configuration you need for SSR like separate server and client entrypoints. For more information check out Vite's Official SSR Documentation
Custom Configuration
This template comes with the infrastructure for SSR, but you have to add a server to handle it. On Freestyle, we recommend using hono
for this. We recommend adding index.js
and installing hono
as a dependency.
npm i hono
Then create a file called index.js
in the root of your project. This file will be the entrypoint for your server.
import fs from "node:fs/promises";
import { Hono } from "hono";
import { serveStatic } from "hono/deno";
import { render } from "./server/entry-server.js";
const templateHtml = await fs.readFile("./client/index.html", "utf-8");
const app = new Hono();
app.get("*", serveStatic({}));
app.get("*", async (c) => {
try {
const url = c.req.url;
const template = templateHtml;
const rendered = render(url);
const html = template
.replace(`<!--app-head-->`, rendered.head ?? "")
.replace(`<!--app-html-->`, rendered.html ?? "");
return c.html(html);
} catch (e) {
console.log(e.stack);
return c.text(e.stack, 500);
}
});
Deno.serve(app.fetch);
Deploying the App
CLI
Install the Freestyle CLI.
npm i freestyle-sh
Now deploy it
npx freestyle deploy --domain some.style.dev --web index.js
API
You can also deploy the app using the API.
Install the Freestyle API client.
npm i freestyle-sandboxes
Then you can use the following code to deploy the app:
import { FreestyleSandboxes } from "freestyle-sandboxes";
import { prepareDirForDeploymentSync } from "freestyle-sandboxes/utils";
// Create a sandboxes client
const sandboxes = new FreestyleSandboxes({
apiKey: process.env.FREESTYLE_API_KEY!,
});
async function deploy() {
await sandboxes.deployWeb(prepareDirForDeploymentSync("."), {
// put whatever domains you want here
domains: ["example.style.dev"],
});
}
deploy();
Finally, to make the deploy happen, run it
bun run deploy.ts
Next Steps
- Now that you can deploy Vite apps to Freestyle, you'll probably want to deploy them to custom domains. To deploy to your own custom domains, you can use the UI in the Freestyle dashboard, and to start building self serve to deploy to your users domains you should check out this guide