Reputation: 101
I have an express graphql endpoint reachable by POST at ${host}/api/graphql
.
On that the route I have authentication middleware and want to redirect to the login page if the user is not logged in.
Looks a little like this.
const authCheck = (req, res, next) => {
const referringUrl = req.get('referer');
try {
const token = req.cookies.Auth;
jwt.verify(token, process.env.AUTH_PRIVATE_KEY);
next();
} catch(err) {
res.redirect(302, `/login?redirect=${referringUrl}`);
}
}
At first I had it as a response status code 307 and it worked fine on GET requests. The browser changes the page to the referringUrl
as expected.
But for Post requests, using a status 307 caused the browser redirect to use the post method. Fine, so I switched to 302. Now it sends a get request but doesn't actually change the url in the browser.
How do I accomplish this functionality from the server side?
Thanks in advance.
Upvotes: 1
Views: 1852
Reputation: 1168
As @regilero said, problem on client side. Your GraphQl server can't change url in browser, because js code makes request, not browser.
You can catch 30* status of error and make redirect manually on your client code.
If you use Apollo Client for graphQl, you can follow this guide https://www.apollographql.com/docs/react/features/error-handling/#network-errors
Upvotes: 2
Reputation: 30496
The redirect After-Post code is generally 303
(See other), this should avoid the reuse of POST method that you had with 307
.
The strange thing is that a 303 is almost the same thing as a 302, and a browser receiving such redirection should follow it and alter the browser location. So your current code should already work.
You said Now it sends a get request but doesn't actually change the url in the browser
so I think you are maybe talking about an Ajax call? If the POST is made via an XhmlHttpRequest then your problem is not only about the serverside. It's about handling redirections in Ajax calls. And then you have several paths that you can follow. You can search for 'redirections' and 'ajax' on stack overflow and find some advices. For example you can build your own application level protocol and not sending an HTTP redirect but an application redirect in a json response, and have the js client understanding it and altering the location, or some other stuff. That's an heavily discussed subject.
By the way in terms of security/robustness you may have some tweaks to do, like using encodeURI
on the location used in your redirect() call and maybe checking that the referer
is from a domain that you really handle (or enforcing relatives urls only on the redirect
argument of your login page).
Upvotes: 1