Can't trigger redirects using edge functions on netlify

I’m doing some research on Netlify and I read that for redirects you can’t use regex as it is not natively supported. Instead I read that you should use edge functions, however they do not seem to appear to be working. AS of now, I’m just trying common logic that can be used on the _redirect just to test if it can actually make a redirect to the url I want it to but to no avail.

The function continues with other cases but I still can’t even make the first case work.

I know netlify is recognizing the edge function since I see these logs:

Aug 14, 09:29:55 AM: 01K2KQRG info   \[category-redirects\] Edge Function triggered for path: /category  
Aug 14, 09:29:55 AM: 01K2KQRG info   \[category-redirects\] Category path detected, processing redirect...  
Aug 14, 09:29:55 AM: 01K2KQRG info   \[category-redirects\] Type parameter: food  
Aug 14, 09:29:55 AM: 01K2KQRG info   \[category-redirects\] Redirecting to /blog?type=food

But still there is no redirection happening and I’m still being shown the home screen despite the url https://stumbleguymod.com/ containing category?type=food.

Here is the code I have:

export default async (req: Request, { cookies, geo }: Context) => {
    const url = new URL(req.url);
    const path = url.pathname;
    const searchParams = url.searchParams;

    console.log(`Edge Function triggered for path: ${path}`);

    // Handle category redirects with complex logic
    if (path === "/category") {
        console.log("Category path detected, processing redirect...");
        const type = searchParams.get("type");
        console.log(`Type parameter: ${type}`);

        if (type) {
            // Validate and transform the type parameter
            const validTypes = ["food", "drinks", "other"];
            const normalizedType = type.toLowerCase().trim();

            if (validTypes.includes(normalizedType)) {
                console.log(`Redirecting to /blog?type=${normalizedType}`);
                // Redirect to blog with the category
                return new URL(`/blog?type=:${normalizedType}`, req.url);
            }
        }

        // If no valid type, redirect to blog without category
        console.log("No valid type, redirecting to /blog");
        return new URL("/blog", req.url);
        // ....
    }
}

@fahadadi Just to clarify, are you trying to redirect or rewrite?

What you have shown would be rewrites based on the documentation here:
https://docs.netlify.com/build/edge-functions/api/#return-a-rewrite

The redirects example is just above that:
https://docs.netlify.com/build/edge-functions/api/#return-a-redirect

1 Like