How to use Vue.js with server-side rendering (SSR)?

To use Vue.js with server-side rendering (SSR), you can follow the steps below:

  1. Install the necessary dependencies:

    npm install vue vue-server-renderer express
  2. Create a new file for your server code (e.g., server.js).

  3. Import the required modules:

    const express = require('express'); const Vue = require('vue'); const renderer = require('vue-server-renderer').createRenderer();
  4. Create an express app:

    const app = express();
  5. Define a route to handle rendering:

    app.get('/', (req, res) => { // Create a new Vue instance const app = new Vue({ template: `<div>Hello World</div>` }); // Render the Vue instance to HTML renderer.renderToString(app, (err, html) => { if (err) { console.error(err); res.status(500).end('Internal Server Error'); } // Send the rendered HTML to the client res.end(` <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Vue SSR Example</title> </head> <body>${html}</body> </html> `); }); });
  6. Start the server:

    app.listen(3000, () => { console.log(`Server started at http://localhost:3000`); });
  7. Run the server:

    node server.js

Now, if you visit http://localhost:3000, you should see "Hello World" displayed on the page. This is a basic example of using Vue.js with server-side rendering (SSR). You can customize it further by using a router, Vuex store, or other Vue.js components.