Hi there,
I am using Apollo Client on a test app which returns JWT tokens in the responses. I am trying to use a "useAfter" middleware to obtain the token on my login/signup graphql requests. I do not want to duplicate logic in the places where login and signup are called, I was thinking I could apply a useAfter middleware to strip the value from the response.
This works, but seems to not be the best way to achieve this:
networkInterface.use([{
applyMiddleware(req, next) {
if (!req.options.headers) {
req.options.headers = {};
}
const token = localStorage.getItem('token');
if (token) {
req.options.headers.token = token;
}
next();
}
}]);
networkInterface.useAfter([{
applyAfterware({ response }, next) {
const responseClone = response.clone();
responseClone.json().then((data) => {
if (data.data.login && data.data.login.token) {
localStorage.setItem('token', data.data.login.token);
}
});
next();
}
}]);
If I try to mess with the response directly without using response.clone
I get this error:
networkInterface.useAfter([{
applyAfterware({ response }, next) {
//const responseClone = response.clone();
response.json().then((data) => {
if (data.data.login && data.data.login.token) {
localStorage.setItem('token', data.data.login.token);
}
});
next();
}
}]);
I tried returning response in next, the entire object etc with no luck:
networkInterface.useAfter([{
applyAfterware({ response }, next) {
//const responseClone = response.clone();
response.json().then((data) => {
if (data.data.login && data.data.login.token) {
localStorage.setItem('token', data.data.login.token);
}
});
next(response);
}
}]);
networkInterface.useAfter([{
applyAfterware(request, next) {
//const responseClone = response.clone();
request.response.json().then((data) => {
if (data.data.login && data.data.login.token) {
localStorage.setItem('token', data.data.login.token);
}
});
next(request);
}
}]);
Am I completely off? What would be the ideal way to globally set a localStorage token?
My test project is here: https://github.com/gregorskii/graphql-udemy-courses/tree/master/auth-graphql
Thanks
@gregorskii I think your approach is correct. Unfortunately you have to clone the response in order to parse it. We know about this problem, and @thebigredgeek has implemented a solution which we'll use in the new network interface that we're starting work on soon.
Awesome thank you for the response.
News?
Most helpful comment
@gregorskii I think your approach is correct. Unfortunately you have to clone the response in order to parse it. We know about this problem, and @thebigredgeek has implemented a solution which we'll use in the new network interface that we're starting work on soon.