Blog>
Snippets

Pre-rendering Vue.js 3 SPA for SEO

Showcase how to pre-render a single-page application built with Vue.js 3 using a prerendering plugin to make it more SEO-friendly.
const { defineConfig } = require('vite');
const vuePlugin = require('@vitejs/plugin-vue');
const prerenderSpaPlugin = require('prerender-spa-plugin');

// Define your routes for static snapshots
const routesToPrerender = [
    '/',
    '/about',
    '/contact',
];

module.exports = defineConfig({
    plugins: [
        vuePlugin(),
        // Prerender SPA Plugin configuration
        prerenderSpaPlugin({
            staticDir: path.join(__dirname, 'dist'), // Directory where your app is built
            routes: routesToPrerender,
            // Optional: other configuration options go here
        }),
    ],
});
This code snippet should be placed in a Vue.js 3 project's `vite.config.js` (if using Vite as the build tool) or similar configuration file to set up pre-rendering for specific routes. It imports necessary plugins and defines the routes to pre-render. When you build your app, it generates static HTML for each of these routes, improving SEO by allowing search engines to crawl the content.
// Pre-rendering Example Component
<template>
  <div>
    <h1>Welcome to Our SPA!</h1>
    <p>This is an example of a pre-rendered Vue.js page.</p>
  </div>
</template>

<script>
export default {
  name: 'ExampleComponent',
  // Other component options
};
</script>
This is a simple Vue.js component that will be pre-rendered using the configuration specified in the previous code snippet. When the app is built, a static HTML version of this component will be generated for SEO purposes.