Blog>
Snippets

Setting up Vue.js 3 with SSR for SEO optimization

Demonstrate the server-side rendering setup using Vue.js 3 and Node.js to improve search engine optimization.
const { createSSRApp } = require('vue');
const { renderToString } = require('@vue/server-renderer');
const express = require('express');

const server = express();

// Define a Vue component
const App = { 
  template: '<div>Hello, SSR!</div>'
};

// Handle all GET requests
server.get('*', async (req, res) => {
  const app = createSSRApp(App);
  try {
    const appContent = await renderToString(app);
    
    const html = `
      <html>
        <head>
          <title>Vue SSR Example</title>
        </head>
        <body>
          ${appContent}
        </body>
      </html>`;

    res.send(html);
  } catch (err) {
    res.status(500).send('Server Error');
  }
});

// Start the server
const PORT = process.env.PORT || 3000;
server.listen(PORT, () => {
  console.log(`Server is running on http://localhost:${PORT}`);
});
This piece of code demonstrates how to set up a Vue.js 3 SSR server with Express. It creates a simple Vue app, transforms it into a server-rendered string, wraps it with basic HTML, and serves it in response to all GET requests. This setup ensures that the content is rendered on the server, which can benefit SEO by serving a fully rendered page to search engine crawlers.