Introduction to Server-Side Rendering

Server-Side Rendering (SSR) in Vue.js allows you to render your Vue components on the server before sending the HTML to the client. This approach is crucial for building universal apps that improve SEO, performance, and user experience. In this guide, we'll explore how to implement SSR in Vue.js and create universal apps.


Setting Up an SSR Project

To create an SSR project in Vue.js, you can use the Vue CLI or a boilerplate like Nuxt.js. Here's a basic example of setting up an SSR project using Vue CLI:


# Install Vue CLI globally
npm install -g @vue/cli
# Create a new Vue project with SSR support
vue create my-ssr-app
cd my-ssr-app
vue add ssr

This sets up an SSR project with the necessary configurations.


Creating SSR Components

SSR components in Vue.js are similar to regular Vue components but have additional methods and configurations for server-side rendering. Here's an example of creating an SSR component:


<template>
<div>
<h2>{{ title }}</h2>
<p>{{ content }}</p>
</div>
</template>
<script>
export default {
async asyncData({ params }) {
const { id } = params;
const response = await fetch(`https://api.example.com/posts/${id}`);
const data = await response.json();
return data;
},
data() {
return {
title: '',
content: '',
};
},
};
</script>

In this example, the `asyncData` method fetches data from an API and initializes the component's data.


Rendering on the Server

To enable SSR, you need a server that renders Vue components on the server side. Here's an example of using Express.js to set up a server for Vue SSR:


const express = require('express');
const { createRenderer } = require('vue-server-renderer');
const server = express();
const renderer = createRenderer();
server.get('*', async (req, res) => {
const app = new Vue({
data: {
url: req.url,
},
template: `<div>Current URL: {{ url }}</div>`,
});
const html = await renderer.renderToString(app);
res.end(html);
});
server.listen(3000, () => {
console.log('Server is running on port 3000');
});

This code demonstrates a basic Express server that renders a Vue component with SSR.


Conclusion

Vue.js Server-Side Rendering (SSR) is a powerful technique for building universal apps that enhance SEO, performance, and user experience. By setting up an SSR project, creating SSR components, and rendering on the server, you can create server-rendered Vue applications.