4 Hours

5. Vite: Plugins, Environment Variables, and SSR

Vite

Vite's plugin system extends its capabilities for advanced use cases. Plugins can transform code, add features, and integrate with other tools. This module covers Vite plugins, environment variables, and Server-Side Rendering (SSR).

The key insight is that Vite's plugin system is simple yet powerful. Plugins can hook into the build lifecycle, transform code, and add features. Environment variables allow configuration across environments. SSR enables server-side rendering for better SEO and performance.

This module covers Vite plugins, environment variables, SSR setup, and deployment.

Vite Plugins

Vite has a rich ecosystem of plugins. Official plugins include: @vitejs/plugin-react (React support), @vitejs/plugin-vue (Vue support), and @vitejs/plugin-legacy (legacy browser support). Community plugins cover everything from PWA to GraphQL. Plugins are easy to install and configure.

Plugins can be used for: framework integration, code transformation, optimization, and feature addition. Understanding plugins is essential for extending Vite's capabilities. Many Rollup plugins also work with Vite.

Environment Variables

Vite supports environment variables through .env files. Variables prefixed with VITE_ are exposed to the client. Other variables are only available in Node.js. Environment variables enable configuration across environments (development, staging, production).

Common use cases: API URLs, feature flags, and authentication tokens. Environment variables should be used for configuration that differs across environments.

JavaScript
// .env.development
VITE_API_URL=http://localhost:3000/api
VITE_FEATURE_FLAG_NEW_UI=true

// .env.production
VITE_API_URL=https://api.example.com
VITE_FEATURE_FLAG_NEW_UI=false

// .env.local (not committed)
VITE_API_KEY=sk_test_123

// Using in code
const apiUrl = import.meta.env.VITE_API_URL;
const featureFlag = import.meta.env.VITE_FEATURE_FLAG_NEW_UI;

// vite.config.js
export default defineConfig({
  define: {
    'process.env.API_URL': JSON.stringify(process.env.API_URL),
  },
});

// Using environment variables in code
// src/api.js
export const api = {
  baseURL: import.meta.env.VITE_API_URL,
  fetch: (url) => fetch(`${import.meta.env.VITE_API_URL}${url}`),
};

Server-Side Rendering (SSR) with Vite

Vite supports Server-Side Rendering for frameworks like React and Vue. SSR improves SEO, performance, and user experience. Vite's SSR is built on top of Node.js and provides tools for server-side rendering of components.

SSR involves: rendering components on the server, hydrating them on the client, and handling routing. Vite's SSR support includes: development server with HMR, production builds, and middleware for Node.js servers.

JavaScript
// server.js - Basic SSR server
import express from 'express';
import { createServer } from 'vite';
import { renderToString } from 'react-dom/server';
import App from './src/App';

const app = express();
const vite = await createServer();

app.use(vite.middlewares);

app.get('*', (req, res) => {
  const html = renderToString(<App />);
  res.send(`
    <!DOCTYPE html>
    <html>
      <head>
        <title>SSR with Vite</title>
        <script type="module" src="/src/entry-client.jsx"></script>
      </head>
      <body>
        <div id="root">${html}
`); }); app.listen(3000); // src/entry-client.jsx - Client hydration import { hydrateRoot } from react-dom/client; import App from ./App; hydrateRoot(document.getElementById(root), ); // src/entry-server.jsx - Server entry import App from ./App; export function render() { return renderToString(); }

Try It Yourself: Advanced Vite Setup

Follow these steps to create an advanced Vite setup with plugins, environment variables, and SSR.

Step 1: Create a Vite project
npm create vite@latest vite-advanced -- --template react<br>cd vite-advanced<br>npm install

Step 2: Install additional plugins
npm install --save-dev @vitejs/plugin-react-refresh<br>npm install --save-dev @types/react @types/react-dom

Step 3: Configure environment variables
Create .env files as shown above.

Step 4: Configure SSR
Create server.js and entry files as shown above.

Step 5: Build and run
npm run build<br>node server.js

Try It Yourself: Add PWA support with vite-plugin-pwa. Add GraphQL integration. Add testing with Vitest.

Knowledge Check

Ready to test your understanding of 5. Vite: Plugins, Environment Variables, and SSR?

Back