Access current `$route.path` inside of nuxt.config.js

Viewed 2373

I want to set og:url in my Nuxt SSR project. I am attempting to do this in the nuxt.config.js file however I can not seem to get access to this.$route.path. This is my current code below.

nuxt.config.js

require('dotenv').config()

export default {
  mode: 'universal',
  target: 'static',

  generate: {
    fallback: true
  },

  env: {
    baseUrl: process.env.BASE_URL || 'http://localhost:3000'
  },

  head: () => ({
    meta: [
      {
        hid: 'og:url',
        name: 'og:url',
        content: process.env.baseUrl + this.$route.path
      },
    ],
  }),
}
1 Answers

You almost had it, the issue is that you're giving an arrow function to head, and so this does not refer to the Nuxt instance, but rather the Javascript object you're exporting in nuxt.config.js.

You can even see this in action by replacing your this.$route.path call with this.mode. You'll see that universal is appended to your content.

Anyways, to fix it, just replace the arrow function with a normal function, which will then give you access to the Nuxt context with this:

require('dotenv').config()

export default {
    mode: 'universal',
    target: 'static',

    generate: {
        fallback: true
    },

    env: {
        baseUrl: process.env.BASE_URL || 'http://localhost:3000'
    },

    head() {
        // this.$route is undefined when generating the fallback page
        const path = this.$route ? process.env.baseUrl + this.$route.path : process.env.baseUrl
        return {
            meta: [
                {
                    hid: 'og:url',
                    name: 'og:url',
                    content: path
                }
            ]
        }
    }
}
Related