I need help on an issue im currently struggling with. I used Vercels platforms starter kit and took the middleware parts for the custom domain rewrites. The rewrites itself do work but when I access the home folder I can also access the pages that should only be accessible via the subdomain (localhost:3000/tickets should not work only test.localhost:3000/tickets should).
I would highly appreciate it if someone could help me.
Here is my middleware:
import { env } from '@/lib/env'
import { Database } from '@/types/supabase'
import { createServerClient } from '@supabase/ssr'
import { NextResponse, type NextRequest } from 'next/server'
export async function middleware(request: NextRequest) {
let response = NextResponse.next()
const url = request.nextUrl
let hostname = request.headers
.get('host')!
.replace('.localhost:3000', `.${process.env.NEXT_PUBLIC_ROOT_DOMAIN}`)
if (
hostname.includes('---') &&
hostname.endsWith(`.${process.env.NEXT_PUBLIC_VERCEL_DEPLOYMENT_SUFFIX}`)
) {
hostname = `${hostname.split('---')[0]}.${
process.env.NEXT_PUBLIC_ROOT_DOMAIN
}`
}
const searchParams = request.nextUrl.searchParams.toString()
const path = `${url.pathname}${
searchParams.length > 0 ? `?${searchParams}` : ''
}`
if (
hostname === 'localhost:3000' ||
hostname === process.env.NEXT_PUBLIC_ROOT_DOMAIN
) {
return NextResponse.rewrite(
new URL(`/home${path === '/' ? '' : path}`, request.url),
)
}
const supabase = createServerClient<Database>(
env.NEXT_PUBLIC_SUPABASE_URL,
env.NEXT_PUBLIC_SUPABASE_ANON_KEY,
{
cookies: {
getAll() {
return request.cookies.getAll()
},
setAll(cookiesToSet) {
cookiesToSet.forEach(({ name, value, options }) =>
response.cookies.set(name, value, options),
)
},
},
},
)
const {
data: { user },
} = await supabase.auth.getUser()
if (hostname == `admin.${process.env.NEXT_PUBLIC_ROOT_DOMAIN}`) {
response = NextResponse.rewrite(
new URL(`/admin${path === '/' ? '' : path}`, request.url),
)
if (!user && path !== '/login') {
return NextResponse.redirect(new URL('/login', request.url))
}
return response
}
response = NextResponse.rewrite(new URL(`/${hostname}${path}`, request.url))
const domain = hostname.split('.')[0]
const { data: workspace } = await supabase
.from('public_workspaces')
.select('domain')
.eq('domain', domain)
.single()
if (!workspace && path !== '/access-denied') {
return NextResponse.redirect(new URL('/access-denied', request.url))
}
if (!user && path !== '/login' && path !== '/access-denied') {
return NextResponse.redirect(new URL('/login', request.url))
}
return response
}
export const config = {
matcher: ['/((?!api/|_next/|_static/|_vercel|[\w-]+\.\w+).*)'],
}
I tried to test if the middleware shows the expected behavior only the part for the home folder rewrite is in the middleware but same result.