Redirects with edge functions

Is there a simple example of doing a redirect with edge functions?

I had assumed I would be able to use Response.redirect() from the Web API:

export default () => new Response.redirect("https://example.com", 302) 

This doesn’t work. Instead I am having to setup the headers and status of the returned response to make a redirect, which I’m guessing I shouldn’t need to do:

export default () => { const headers = { Location: 'http://example.com' } const init = { status: 302, headers } return new Response("do it!", init) } 

Am I missing a cleaner way?

Hey @sanscheese

Looking at the Web API documentation for Edge Functions, redirect is not supported (currently at least), so you need to use the Location header method.

1 Like

You can use the Response.redirect() method. It is a method, not a class, so you have to skip the new prefix.

See my gist for an example

1 Like

Is is possible to do rewrite/proxy? I want to implement A/B testing between netlify sites based on cookie value sent by browser.

Thank you! You are right, and I was sure I had it working like this the other day :smile:

Turns out I tried to set a cookie above the redirect which was resulting in an error:
Error: TypeError: Headers are immutable.

Removing that means this is enough for minimal redirect example:

export default () => Response.redirect("https://icanhazdadjoke.com/", 302) 

(I should have tested my minimal example before posting!)

rewrite/proxy are possible
rewrite example: Rewrite with Edge Functions | Edge Functions on Netlify
Proxy example: Proxy requests to another source | Edge Functions on Netlify

1 Like

Ah yes, of course, should have spotted the errant new.

Best my understanding, no headers, etc, are settable with Response.redirect(), so use case would dictate method used.

2 Likes

Hi all.

First of all, I wanted to thank everyone who chimed in on this thread and helped find a workaround for the cookies + Response.redirect limitation. Your contributions are much appreciated!

Improving the Edge Functions experience is something we’ve been actively working on, and so I wanted to share an update on this specific use case.

It is now possible to set cookies (either by using the context.cookies.set utility method or by setting the set-cookie header manually) and return a redirect constructed with Response.redirect.

Additionally, Response.redirect now accepts a relative path, which means you can use it without having to provide the full URL.

Example:

import type { Context } from "https://edge.netlify.com"; export default async (req: Request, context: Context) => { context.cookies.set({ name: "my-cookie-1", value: "chocolate-chip", expires: new Date("2028-12-31"), }); return Response.redirect("/new-path"); }; 

This is available with version 13.1.0 of the Netlify CLI.

If you’re still experiencing any issues, please us know on this thread.

Thanks again and happy builds! :rocket:

4 Likes