1

I've recently migrated my project to NextJS 13 AppDir and I'm encountering redirection issues. My category pages have dynamic URLs, and I need to validate whether a visitor types a brand name or a category name in the URL, such as "domain.com/adidas" or "domain.com/jeans". To achieve this, I'm checking the slug against my list of brands or categories to determine if the visitor is trying to access a brand page or a category page, in accordance with our company's URL structure policy.

However, for cases where an old category URL is accessed, I need to redirect it to a new one. Here's the code snippet I'm using for this purpose:

//page.js
const generatedSlug = [entityResult.category?.slug, ...entityResult.brands.map(x => x.slug)]
    .map(x => x?.replace(/\//g, ''))
    .filter(Boolean)
    .join('/');

const compareSlug = slug.join('/');

if (generatedSlug !== compareSlug) {
    const searchParamString = searchParams && Object.keys(searchParams).length
        ? '?' + new URLSearchParams(searchParams).toString()
        : '';

    redirect(`/${generatedSlug}${searchParamString}`);
}

The issue I'm facing is that the redirection using redirect from "next/navigation" results in a 307 redirect status. I've been trying to find a way to indicate a 301 redirect status, but so far, I haven't been successful. Is there a way to achieve a 301 redirect status in this context?

P.S: I attempted to use middleware to address this issue. While it worked, I faced a challenge. The middleware doesn't cache the categories and brands retrieved from certain endpoints, making it impossible to revalidate whenever there are changes. Additionally, I explored using the FileSystem approach within middleware, but it only operates in the Edge runtime and isn't available in other contexts. Is there an alternative solution that would allow me to efficiently manage caching and achieve the desired redirection behavior maybe?

T. Cem Yılmaz
  • 500
  • 9
  • 30

0 Answers0