t3rmian / devpot

A coder's blog
https://blog.termian.dev
1 stars 0 forks source link

posts/netlify-serverless-redirect/ #123

Open utterances-bot opened 1 year ago

utterances-bot commented 1 year ago

Netlify redirects using serverless functions

https://blog.termian.dev/posts/netlify-serverless-redirect/

OxideManganese commented 1 year ago

Thank you for the helpful article. Can you tell me if there is a way to redirect without passing Parameters?

t3rmian commented 1 year ago

Hi @OxideManganese Yes, it is possible to redirect without passing parameters in the URL. Instead of appending the query parameters to the redirected URL, you can omit them altogether.

Here's an updated version of the Netlify function that redirects without passing the parameters:

exports.handler = async function (event) {
    const lang = event.queryStringParameters.state?.split("-")[0] ?? "en";
    return {
        statusCode: 302,
        headers: {
            "Location": `/${lang}${event.path}`,
        },
    };
};

For example, if the original URL is /campaign?param1=value1&param2=value2&state=en-XXXX-XXXX, the user will be redirected to /en/campaign without the query parameters. If, however, you don't want to pass parameters or any other distinctive information (the docs provide access to the full request) to the serverless function, then this approach might lose its purpose. You can do simple redirecting using Netlify configuration.

What's also interesting is that Netlify has just introduced Edge Functions into general availability. These are supposed to run much closer to the user than the standard serverless, potentially reducing the latency.