How to Set Up Vite for Server-Side Rendering (SSR)?
Last Updated :
21 Aug, 2024
Vite is a build tool that can be integrated with most modern JS web frameworks like React, Vue, Next.js, or even vanillaJS, and offers a variety of features like Hot Module Reloading (HMR), etc. In this article, we will learn how to setup vite using vanillaJS and SSR.
Steps to Set Up Vite for Server-Side Rendering (SSR)
Step 1: Create a vanillaJS vite project using the below commands
npm create vite@latest vite-ssr // select VanillaJS here while creating the project
cd vite-ssr
npm i
Project structure:
Project structureStep 2: Create an index.html file inside the "src" dir
In this step, we will create an index.html file that we will send to the client when the server is started and the user goes to the root page ("/"). This file will render a button in the UI.
HTML
<!--src/index.html -->
<html lang="en">
<head>
<title>Vite SSR</title>
</head>
<body>
<div id="app"></div>
<button id="button">Load Content</button>
<script defer type="module" src="/src/main.js"></script>
</body>
</html>
Step 3: Create a main.js file that we will run when the button is clicked
Create a main.js file that will mount the app and display a static text content when the button in the UI is clicked.
JavaScript
// src/main.js
const button = document.getElementById("button");
button.addEventListener("click", () => {
const app = createApp();
app.mount("#app");
});
function createApp() {
const app = document.createElement("div");
app.id = "app";
app.textContent = "Hello, Vite SSR with Vanilla JS!";
return {
mount(selector) {
document.querySelector(selector).appendChild(app);
},
};
}
Step 4: Create a server file that we will handle the requests from client
Create a server.js file that will return the index.html and main.js files upon requests from the client.
JavaScript
// src/server.js
import express from "express";
import path from "path";
const __dirname = path.resolve();
const app = express();
app.get("/", (req, res) => {
res.sendFile(path.join(__dirname, "src", "index.html"));
});
app.get("/src/main.js", (req, res) => {
res.sendFile(path.join(__dirname, "src", "main.js"));
});
app.listen(3000, () => {
console.log("Server is running on http://localhost:3000");
});
Step 5: Add configurations in vite config file:
Create a vite.config.js file and add configurations so that the root dir is pointed to "src".
JavaScript
// vite.config.js
export default {
root: "src",
build: {
outDir: "../dist",
},
};
Step 6: Run the application
Start the application server to see the output:
node src/server.js
Output:
Output