Snippet injection

Often you want to inject JavaScript snippets into all pages of your site, either in the <head> or at the end of the <body> tag.

Most analytics providers, retargeting services, and A/B testing services will give you an HTML snippet and ask you to add it to every page on your site. Netlify lets you do this without having to pollute the source code for the site with production specific analytics snippets.

You can pick between injecting the scripts before the closing </head> tag or before the closing </body> tag.


Injected snippets will also show up on the password protection screen. This means you can verify that your analytics scripts are correctly configured without having to remove the password when your site is still under development.

# Limitations

Snippet injection occurs when pages are served, not when they’re built. This means there are some things to consider when using snippets.

  • If you are proxying content to your site, snippets won’t be injected. Instead, the site or service should provide a complete response, including any necessary data.
  • If a route is handled by a function, snippets won’t be injected. Because server side rendering (SSR) on Netlify uses Netlify Functions, snippets won’t be injected on SSR pages. The serverless functions that handle those pages should return a complete response, including any HTML that you might otherwise use our snippet injection feature for.

# Snippet injection UI

In Site settings > Build & Deploy > Post processing, find the Snippet Injection section and select Add Snippet. Then give your snippet a name and paste the snippet body (including any <script> tags if you’re adding a script, etc).

# API endpoints

You can use the API to get snippets, add snippets, and more.

# Environment variables

Injected snippets can access some environment variables in each deploy context. Along with environment variables that you create, you can also access these Netlify read-only variables:

  • URL

As snippet injection uses Liquid template syntax, you can access environment variables in snippets using the format {{VARIABLE_NAME}}.

For example, to add a note to your Deploy Preview to remind visitors that they’re accessing a preview version of your site, you can create an HTML snippet to inject before the closing </body> tag that contains the following:

{% if {{CONTEXT}} == 'deploy-preview' %}
  <h1>Hello! This is a preview version of our site.</h1>
{% endif %}

Netlify will inject this snippet into your site’s pages as they are served. If the value of the CONTEXT environment variable on the site is deploy-preview, the message will display at the bottom of each page.

Another example of how you might use environment variables in snippets is to add analytics scripts for split testing.

# More resources