Vue.js Check/Detect Is Prerender Environment

December 10, 2019

You are using prerender-spa-plugin, and you want to know if you are in prerender environment.

Edit vue.config.js.

const path = require('path')
const PrerenderSPAPlugin = require('prerender-spa-plugin')
const Renderer = PrerenderSPAPlugin.PuppeteerRenderer

module.exports = {
  configureWebpack:  {
    plugins: process.env.NODE_ENV === 'production' ? [
      new PrerenderSPAPlugin({
        // Required - The path to the webpack-outputted app to prerender.
        staticDir: path.join(__dirname, 'dist'),
        // To check/detect is prerender environment
        renderer: new Renderer({
          injectProperty: '__PRERENDER_INJECTED',
          inject: { // required, else window['__PRERENDER_INJECTED'] is not created
            foo: 'bar'
          },
        }),
        // Required - Routes to render.
        routes: [ '/', '/about', '/day/2019-10-18', '/card/qGNpbK3R7ne0siTNPTya'],
      })
    ] : []
  }
}

Runtime check

const isPrerender = '__PRERENDER_INJECTED' in window
This work is licensed under a
Creative Commons Attribution-NonCommercial 4.0 International License.