nuxt.jsnuxt3.js

How to get current domain at Nuxt 3 middleware?


I can't use window.location here because it's SSR app. useRouter, useRoute, and useNuxtApp don't have domain name too. nuxtApp.ssrContext is undefined.

export default defineNuxtRouteMiddleware((to: any, from: any) => {
  console.log("GET HOST HERE")
})

Solution

  • The helper function useRequestURL() was introduced with the release of v3.5.0 of Nuxt. Getting the current url, the protocol scheme, the host, the hostname and the path is very easy:

    const url = useRequestURL()
    
    const currentUrl = url.href     // https://example.com:3000/hello-world    
    const protocol = url.protocol   // https:
    const host = url.host           // example.com:3000
    const hostname = url.hostname   // example.com
    const pathname = url.pathname   // /hello-world
    

    or if only the hostname is needed we can access the object property directly:

    const hostname = useRequestURL().hostname
    

    Since useRequestURL() works on both server-side and client-side there is no need to check for the process.server. The function returns the familiar URL object which properties with their descriptions can be found in the MDN documentation.

    Nuxt have updated their documentation and the description of the useRequestURL() can be found in the Composables section.