Vite

Injecting environment-specific HTML tags with Vite

Use transformIndexHtml and HtmlTagDescriptor to configure entry HTML, crawler directives, social metadata, and scripts per deployment mode.

Injecting environment-specific HTML tags with Vite

My development, staging, and production deployments needed different entry HTML. I used Vite’s transformIndexHtml hook to inject environment markers, social metadata, and externally hosted scripts without maintaining several copies of the template.

Deciding which deployment owns each tag

An SPA’s index.html is an entry to the application graph. It is also the earliest place to set the document title, crawl directives, and metadata that a social preview bot may read before JavaScript executes.

I use a visible development banner and build marker to prevent testers from confusing a local instance with production. A noindex directive can ask cooperative search crawlers to exclude a public staging document. Access control still belongs on the server. Production alone needs analytics or public CDN scripts. A deployment table makes policy changes explicit.

EnvironmentUseful tagsDeployment concerns
Local devEnvironment marker, banner, crawl directiveKeep the template easy to inspect
StagingExplicit mode marker or crawl directiveGate access by the deployment, and keep real analytics disabled
ProductionOpen Graph metadata and approved external scriptsVerify actual deployment mode and resource policy

Choosing how the HTML hook returns values

Vite calls transformIndexHtml when it processes an entry HTML document in development or for a build. A hook can return a replacement string, an array of descriptors, or an object with both HTML and tags. Vite transformIndexHtml

flowchart TD
    RawHtml["Read index.html"] --> HookCall["Run HTML hook"]
    subgraph DescriptorProcessing["Place tag descriptors"]
        direction TB
        HeadPrepend["head-prepend"]
        Head["head"]
        BodyPrepend["body-prepend"]
        Body["body"]
        HeadPrepend --> Head --> BodyPrepend --> Body
    end
    HookCall --> HeadPrepend
    Body --> FinalHtml["Serve or write HTML"]

A direct string replacement can be enough for a tightly controlled title.

1
2
3
transformIndexHtml(html) {
  return html.replace(/<title>(.*?)<\/title>/, '<title>New title</title>');
}

Once several tags need independent placement, I use descriptors. Vite accepts this shape.

1
2
3
4
5
6
export interface HtmlTagDescriptor {
  tag: string;
  attrs?: Record<string, string | boolean | undefined>;
  children?: string | HtmlTagDescriptor[];
  injectTo?: 'head' | 'body' | 'head-prepend' | 'body-prepend';
}

injectTo tells Vite whether the tag belongs in the head or body and whether it should precede the other contents. This avoids replacements that accidentally match a tag inside a comment or an attribute. The hook’s order: 'pre' is useful when an injected resource has to pass through Vite’s normal HTML processing.

Building the environment plugin

The plugin records the resolved configuration and chooses its tags from the active environment. Common metadata is declared once. Development adds debug information and a banner. Production adds Open Graph information and optional external resources.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
// plugins/vite-plugin-html-env.ts
import type { Plugin, HtmlTagDescriptor, IndexHtmlTransformContext } from 'vite';

export interface HtmlEnvOptions {
  siteTitle: string;
  canonicalUrl?: string;
  gtmId?: string;
  enableCdn?: boolean;
}

export function htmlEnvPlugin(options: HtmlEnvOptions): Plugin {
  let isProduction = false;

  return {
    name: 'vite-plugin-html-env',

    configResolved(config) {
      isProduction = config.mode === 'production';
    },

    transformIndexHtml: {
      order: 'pre', // Run before ordinary HTML transforms
      handler(html: string, ctx: IndexHtmlTransformContext): HtmlTagDescriptor[] {
        const tags: HtmlTagDescriptor[] = [];

        // 1. Configure the shared title
        const titleText = isProduction ? options.siteTitle : `[DEV] ${options.siteTitle}`;
        tags.push({
          tag: 'title',
          children: titleText,
          injectTo: 'head',
        });

        if (!isProduction) {
          // 2. Add development metadata and the banner
          tags.push(
            {
              tag: 'meta',
              attrs: { name: 'robots', content: 'noindex, nofollow' },
              injectTo: 'head',
            },
            {
              tag: 'meta',
              attrs: { name: 'app:env', content: 'development' },
              injectTo: 'head',
            },
            {
              tag: 'meta',
              attrs: { name: 'app:git-branch', content: 'feature/seo-transform' },
              injectTo: 'head',
            },
            {
              tag: 'div',
              attrs: {
                id: 'dev-banner',
                style: 'background:#f38ba8;color:#11111b;text-align:center;font-size:12px;padding:4px;font-weight:bold;',
              },
              children: '⚠️ LOCAL DEVELOPMENT ENVIRONMENT - DO NOT USE FOR PROD DATA',
              injectTo: 'body-prepend',
            }
          );
        } else {
          // 3. Add production Open Graph metadata and scripts
          tags.push(
            {
              tag: 'meta',
              attrs: { property: 'og:title', content: options.siteTitle },
              injectTo: 'head',
            },
            {
              tag: 'meta',
              attrs: { property: 'og:type', content: 'website' },
              injectTo: 'head',
            },
            {
              tag: 'meta',
              attrs: { property: 'og:url', content: options.canonicalUrl || 'https://namju.kim' },
              injectTo: 'head',
            },
            {
              tag: 'meta',
              attrs: { property: 'og:image', content: `${options.canonicalUrl}/assets/images/og-main.png` },
              injectTo: 'head',
            }
          );

          if (options.gtmId) {
            tags.push({
              tag: 'script',
              attrs: {
                src: `https://www.googletagmanager.com/gtag/js?id=${options.gtmId}`,
                async: true,
              },
              injectTo: 'head',
            });
          }

          if (options.enableCdn) {
            tags.push({
              tag: 'script',
              attrs: {
                src: 'https://esm.sh/react@18.3.1',
                crossorigin: true,
              },
              injectTo: 'head',
            });
          }
        }

        return tags;
      },
    },
  };
}

Register the plugin with its site title and deployment metadata.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
// vite.config.ts
import { defineConfig } from 'vite';
import { htmlEnvPlugin } from './plugins/vite-plugin-html-env';

export default defineConfig({
  plugins: [
    htmlEnvPlugin({
      siteTitle: 'Commit Log Dashboard',
      canonicalUrl: 'https://namju.kim',
      gtmId: 'G-TRACKER99',
      enableCdn: true,
    }),
  ],
});

A build mode name and the command are separate inputs. Treat a production build using a staging mode as a separate case instead of assuming every invocation of vite build should load production analytics. If the same artifact is promoted between environments, put dynamic configuration at serve time rather than baking different deployment state into one HTML file.

Inspecting the two HTML outputs

Injected development metadata and banner in the entry HTML Figure 1. The development response includes its environment and crawl metadata.

Start npm run dev and inspect the HTTP response. The captured development HTML contains noindex, nofollow and app:env: development in the head. The debug banner appears at the start of the body.

Built HTML showing production Open Graph tags and external scripts Figure 2. Production tags in the built entry HTML.

Run npm run build --mode production and inspect dist/index.html. The development-only elements should disappear. Check og:title, og:image, and og:url against the actual production origin. Verify the GTM script or CDN entry appears only when configured. HTML formatting and minification can vary with the build toolchain.

Checking ordering, security, and external dependencies

I use head-prepend for metadata that must be processed early, and prefer a response header for a Content Security Policy where the hosting setup supports one. Treat script URLs and any descriptor contents as public deployment configuration and apply the site’s allowlists and consent behavior to third-party trackers.

Adding a CDN script does not remove the same package from an application bundle. Externalization and module resolution also need to agree on how browser imports obtain that dependency. Check both the emitted JavaScript and the browser at runtime.

  • Inspect the served and built documents with the expected mode and script settings.
  • Ensure crawl and analytics behavior are separately tested for staging.
  • Check the page with optional external resources unavailable.
  • Give each plugin a clear owner for the title and metadata so multiple hooks cannot emit competing tags.
This post is licensed under CC BY 4.0 by the author.