vite server side rendering in typescript

To set up a Vite Server-Side Rendering (SSR) project with Typescript and Vue3, you need to follow these steps:

  1. First, install the following required dependencies:
index.ts
npm install vue vue-router vite vite-plugin-ssr @types/node @types/vue @types/express jsdom source-map-support
111 chars
2 lines
  1. Next, create a vite.config.ts file in the root of your application with the following contents:
index.ts
import { defineConfig } from 'vite';
import vue from '@vitejs/plugin-vue';
import ssr from 'vite-plugin-ssr/plugin';

export default defineConfig({
  plugins: [vue(), ssr()],
});
179 chars
8 lines
  1. Create an src/index.ts file that exports a Vue app instance:
index.ts
import { createApp } from 'vue';
import App from './App.vue';
import { createRouter, createMemoryHistory } from 'vue-router';

const routes = [
  {
    path: '/',
    component: App,
  },
];

const router = createRouter({
  history: createMemoryHistory(),
  routes,
});

const app = createApp(App);

app.use(router);

export { app, router };
342 chars
22 lines
  1. Create a src/App.vue file with your application's root component.

  2. Create a src/server.ts file to set up the server and serve the application:

index.ts
import { createServer } from 'http';
import { parse } from 'url';
import { app, router } from './index';
import { renderToString } from '@vue/server-renderer';

const server = createServer((req, res) => {
  const { pathname } = parse(req.url || '/', true);
  if (pathname === '/') {
    renderToString(app)
      .then((html) => {
        res.statusCode = 200;
        res.setHeader('Content-Type', 'text/html');
        res.end(html);
      })
      .catch((err) => {
        console.error(err);
        res.statusCode = 500;
        res.end('Internal Server Error');
      });
  } else {
    router
      .resolve({
        url: pathname,
      })
      .then((route) => {
        if (route.redirected) {
          res.writeHead(302, {
            Location: route.redirectedFrom || '/',
          });
          res.end();
          return;
        }

        const matchedComponents = Object.values(route.matched).map(
          (route: any) => route.components.default
        );

        Promise.all(
          matchedComponents.map((component) =>
            component.preFetch ? component.preFetch() : null
          )
        )
          .then(() => {
            renderToString(app, {
              url: req.url,
            })
              .then((html) => {
                res.statusCode = 200;
                res.setHeader('Content-Type', 'text/html');
                res.end(html);
              })
              .catch((err) => {
                console.error(err);
                res.statusCode = 500;
                res.end('Internal Server Error');
              });
          })
          .catch((err) => {
            console.error(err);
            res.statusCode = 500;
            res.end('Internal Server Error');
          });
      })
      .catch((err) => {
        console.error(err);
        res.statusCode = 500;
        res.end('Internal Server Error');
      });
  }
});

server.listen(3000, () => {
  console.log('Server running at http://localhost:3000');
});
1997 chars
75 lines
  1. Run the server by running the following command:
index.ts
npm run dev
12 chars
2 lines

This should start the server at http://localhost:3000 and you should be able to navigate your application by entering URLs in your browser.

gistlibby LogSnag