Need Help Setting Up Dynamic Subdomain Redirects in a Static Nuxt3 Site

Hello Netlify Community,

I’m working on a project where I have a static website built with Nuxt.js (with SSR turned off) and hosted on Netlify. I’m facing a challenge with setting up dynamic redirects based on subdomains and would greatly appreciate any guidance or assistance you can provide.

Goal:

I want to dynamically rewrite URLs based on subdomains. Specifically, when a user accesses a URL with a pattern like [broker-name].dil.dev, I want it to internally rewrite to www.dil.dev/brokers/[broker-name].

Current Setup:

  • I have a wildcard DNS record set up: *.dil.dev CNAME brokerbacon.netlify.app.
  • My Netlify site has wildcard subdomains enabled.
  • I tried setting up a redirect rule in my _redirects file as follows:
[[redirects]]
  from = "https://:broker.dil.dev/*"
  to = "https://www.dil.dev/brokers/:broker/:splat"
  status = 200
  force = true

Issue:

Despite the above configuration, all subdomain traffic is being directed to the root (/) instead of the intended /brokers/[broker-name] path. I understand that placeholders and splats in Netlify redirect rules are for path segments and do not apply to subdomains (please confirm). Hence, my current setup is not achieving the desired result.

Questions:

  1. Is there a way to configure Netlify to dynamically handle these subdomain rewrites within the static site setup?
  2. If not directly possible through static redirects, would Netlify Functions be a viable approach to achieve this? If so, could you provide some guidance or an example on how to set up a function for this purpose?
  3. Are there any best practices or alternative approaches you would recommend for this scenario?

I’m open to any suggestions or insights you might have. Thank you in advance for your time and assistance!

You need Netlify Edge Functions for that. Redirects won’t work.

Not specifically. Once you write the rewrites in the Edge Functions, it should work.

Thanks for the quick reply. I’ll dig into it and let you know how it goes.

I’m encountering an issue with dynamic subdomain handling on my static Nuxt.js site hosted on Netlify. I need to dynamically redirect [broker-name].dil.dev to www.dil.dev/brokers/[broker-name]. However, I’ve run into a limitation with Netlify Edge Functions.

Code Snippet:

export default async (request, context) => {
  const url = new URL(request.url)
  const hostname = url.hostname
  const subdomainParts = hostname.split('.')

  // Check if there is a subdomain
  if (
    subdomainParts.length > 2 ||
    (subdomainParts.length === 2 && hostname.includes('localhost'))
  ) {
    const subdomain = subdomainParts[0]

    // Rewrite the path if subdomain is not 'www'
    if (subdomain !== 'www') {
      const newPath = `/brokers/${subdomain}`
      if (!url.pathname.startsWith(newPath)) {
        // Construct the new URL with 'www' subdomain or the main domain
        const newUrl = new URL(
          `${newPath}${url.pathname}`,
          `https://www.dil.dev`,
        )

        console.log('Rewriting to new URL:', newUrl.toString())
        return newUrl
      }
    }
  }

  // Let the request through as normal for 'www' subdomain or no subdomain
  // return request;
}

export const config = {
  path: '/*',
}

Error Encountered

Error - Rewrite to 'https://www.dil.dev/brokers/1da/' is not allowed: edge functions can only rewrite requests to the same base URL

Can you suggest a workaround within Netlify that would allow me to handle dynamic subdomain rewrites to a subfolder on main site in a static site setup?

You can use fetch() and serve the received response.

I still cant figure it out what I’m doing wrong. I’ve constructed a simple version where I trying to rewrite from a subdirectory rather then the goal (subdomain)

import type { Config } from '@netlify/edge-functions'

export default async () => {
  const url = 'http://www.dil.dev/brokers/1da/'

  try {
    const response = await fetch(url, {
      headers: { Accept: 'text/html' },
    })

    if (!response.ok) {
      throw new Error(`HTTP error! Status: ${response.status}`)
    }

    const contentType = response.headers.get('Content-Type') || 'text/html'
    const htmlContent = await response.text()
    return new Response(htmlContent, {
      headers: { 'Content-Type': contentType },
    })
  } catch (error) {
    console.error('Fetch Error:', error)
    return new Response('Error fetching HTML content', { status: 500 })
  }
}

export const config: Config = {
  path: '/rewrite',
}

if I remove the headers here I see non render html.

    return new Response(htmlContent, {
      headers: { 'Content-Type': contentType },
    })

The code is giving me mime errors.

Failed to load module script: Expected a JavaScript module script but the server responded with a MIME type of "text/html". Strict MIME type checking is enforced for module scripts per HTML spec.

Any ideas what I’m doing wrong?

That error doesn’t make any sense :thinking: . Where can we reproduce this?

@hrishikesh its something todo with Nuxt 3 redirecting after the edge function rewrites the page.

I noticed you answered on this thread about using _redirects instead of the netlify.toml.

I tried adding a _redirect file

/hello-template /brokers 200

but I just got this Vue error

[Vue Router warn]: No match found for location with path "/rewrite/index.htm"

Still trying to figure it out. Any more help would be much appreciated. Thank you

I’ve got a little closer.

If I add a blank app/routes.options.ts, it stops the redirecting… I’m assuming because I broke the redirecting be not exporting a default in the file.

Rewrites work now, but need to fix routes.options.ts now.

Where exactly?

If you can let us know a way to reproduce the issue, we can check.