Redirect to Page and Send Custom Http Headers

Set custom header then redirect

The redirection works but I can't find the test header in the GET request to mysite.com, why ?

Because you set a response header.

There is no way to trigger an HTTP redirect and cause the client to add a custom header.

The only way for a site to make a browser issue an HTTP request with a custom header is to use JavaScript and the XMLHttpRequest object. Since you said you are dealing with an external site, you'd also need to make sure that site implemented CORS to give your site permission.

Adding custom header in HTTP before redirect

I suppose you mean redirecting by window.location.

It's impossible to redirect to a page with custom headers set, no matter what language or framework you use. In other words, there's no way to trigger an HTTP redirect and cause the client to add a custom header.

The only way for a site to instruct a browser to issue an HTTP request with a custom header is to use the XMLHttpRequest object. And it needs CORS implemented on the target server to allow such ajax requests.

The closest workaround you can come up with would be to act as a proxy. e.g., Send ajax requests with custom HTTP headers set, retrieve the response and inject it into the DOM which is a case for building upon the wrong idea.

How to set HTTP headers for client (browser) while sending a response containing the headers to be set and the redirect url from backend (Node.js)?

When you do res.redirect(), the browser will NOT apply the headers you set on that response to the redirected request. Those headers are part of the response back to the requesting client and that's all. They will NOT be sent with the redirected request.

Headers on the redirected request cannot be controlled by the server. Browsers just don't work that way so you can't design things that way if you're relying on a standard browser to be the client.

If you're using redirection and you want something sent back with the redirection, then your best option is typically to put stuff into a cookie or into the query string of the redirect URL. That cookie or query string will be sent with the redirected request and the server can get it from there.

You could also establish a server-side session and put data into that session. This will set a session cookie which will be present on future client requests and the server can then access data from the server-side session object on future requests from that client.



Related Topics



Leave a reply



Submit