GraphQL redirect when resolver throws error
Here's how I implemented this.
On the server side:
// Setup
export default class UnauthorizedError extends Error {
constructor({statusCode = 401, url}) {
super('Unauthorized request to ' + url);
this.statusCode = statusCode;
}
}
// In a resolver
throw new UnauthorizedError({url});
// Setup of the request handler
graphqlExpress(async (req, res) => ({
schema: ...,
formatError(error) {
if (error.originalError instanceof UnauthorizedError) {
res.status(error.originalError.statusCode);
res.set('Location', 'http://domain.tld/login');
} else {
res.status(500);
}
return error;
},
});
On the client side:
const networkInterface = createNetworkInterface();
networkInterface.useAfter([{
applyAfterware({response}, next) {
if ([401, 403].includes(response.status)) {
document.location = response.headers.get('Location');
} else {
next();
}
}
}]);
In Apollo Client 2.0, you can probably use apollo-link-error on the client side for this.