rafaelalmeidatk / TIL

I learn something new almost everyday. Here I post stuff to my future self and to other people that may need it
4 stars 0 forks source link

How to forward headers on redirects #3

Open rafaelalmeidatk opened 4 years ago

rafaelalmeidatk commented 4 years ago

TL;DR: you can't. You have to use cookies or query strings instead.


When I need to redirect the user to another page I often code it like this:

res.writeHead(302, {
  Location: '/somewhere',
});
res.end();

And I had a case where I needed to send some headers with the redirect, so I thought this could work:

res.writeHead(302, {
  Location: '/somewhere',
  Foo: 'bar'
});

But turns out that the browser ignores our "custom" headers and doesn't send them in the new request. It makes sense, but how could I send the data I want to the /somewhere page? The solution is to either use cookies or query strings.

With cookies

If the cookie is already set, you don't need to do anything since the page will be able to read it as usual. But turns out you can also define them in the headers of the redirect, so this will still work:

res.writeHead(302, {
  Location: '/somewhere',
  'Set-Cookie': 'foo=bar'
});

Depending on what you doing you could delete the cookie on /somewhere right after reading it.

With query strings

A simpler solution is to use query strings. You can send the value directly in the URL and it will work fine:

res.writeHead(302, {
  Location: '/somewhere?foo=bar',
});