Strange behaviour when redirecting using `Location` when site is live

Hi. I’ve implemented a feature to redirect all external links on my website by passing them a netlify function. With netlify dev, everything works fine. When I open http://localhost:8888/redirect?to=https://www.instagram.com/netlify, I end up on Netlify (@netlify) • Instagram photos and videos.

But when I deploy the site (cannot give the URL here), opening http://deployed-website.com/redirect?to=https://www.instagram.com/netlify, brings me to Netlify (@netlify) • Instagram photos and videos. I don’t understand why I got the to query here and only on deployed site.

Here is a part of my function code:

// `to` is required by redirect rule in netlify.toml file
const param_to = event.queryStringParameters?.to
const decodedURI = decodeURIComponent(param_to)
const source = decodedURI !== param_to ? decodedURI : param_to

// ...

return {
  statusCode: 302,
  headers: {
    "Location": decodedURI
  }
}

Thanks for help.

Netlify preserves the query params. You need to override those if you wish to get rid of them. So you’d have to build a new URL with a different query param so it would be removed.

Thank you for your answer. I knew that Netlify preserves query params. But the decodedURI has no param at all.

Suppose it had parameters, the solution would be something like this?

// ...
const redirectTo = new URL(decodedURI);
redirectTo.searchParams.delete('to');

return {
  statusCode: 302,
  headers: {
    "Location": redirectTo.toString(),
  },
};

My previously proposed solution doesn’t work. Does anyone have something this case, please?

As I mentioned, you need to send a comletely different query param. If you don’t send any query params, the current ones would be preserved.

Okay, I see. I hadn’t understood, thank you very much. I created an unnecessary ref=mydomain.ext query parameter and it works.