Welcome back to CodeYourCraft! Today, we're diving into Server-Side Rendering (SSR) using Vite JS. Let's get started! 🎯
Server-Side Rendering (SSR) is a technique used in web development where the server generates and returns the complete HTML page to the browser, instead of relying on the client-side JavaScript to create the page. SSR provides several benefits, including better SEO, faster initial load times, and improved user experience. 💡
Vite JS is a modern front-end build tool that offers faster development and production builds. Combining Vite JS with SSR allows us to enjoy the benefits of both technologies: fast development with Vite and server-side rendering for improved SEO and performance. 📝
Before we dive into the code, let's set up our project using Vite.
npm install -g vitevite create ssr-example
cd ssr-examplenpm install vite-plugin-ssrvite.config.js file:import ssr from 'vite-plugin-ssr'
export default {
plugins: [ssr()]
}Now, let's create our first server-side rendered component.
Create a new file named index.server.js in the src folder.
Add the following code:
import { createSSRApp } from 'vue'
import App from './App.vue'
export function createServerRenderer() {
const app = createSSRApp(App)
async function render(url) {
const { appHtml, appCss } = await app.ssrRender({ url })
return {
html: `<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
${appCss}
</head>
<body>
${appHtml}
</body>
</html>`,
statusCode: app.ssrContext.statusCode,
}
}
return { render }
}src/App.vue file:<template>
<div>
<h1>Welcome to CodeYourCraft SSR Example!</h1>
</div>
</template>Now, let's set up our server to render the SSR component.
Create a new file named server.js in the src folder.
Add the following code:
import { createServer } from 'http'
import { render } from './index.server'
const app = createServer(async (req, res) => {
const url = req.url
try {
const { html, statusCode } = await render(url)
res.writeHead(statusCode)
res.end(html)
} catch (error) {
console.error(error)
res.writeHead(500)
res.end('Internal Server Error')
}
})
app.listen(3000, () => {
console.log('Server running on port 3000')
})Now, let's run our server and check out the SSR example:
npm run devOpen your browser and visit http://localhost:3000. You should see the "Welcome to CodeYourCraft SSR Example!" message. ✅
What is Server-Side Rendering (SSR)?
That's it for today! In the next lesson, we'll explore how to create dynamic server-side rendered components using Vite JS. Until then, keep coding, and happy learning! 🚀