Unable to clear apollo-client cache on logout - graphql

I have read through a couple other posts as well as a few github issues, and I am yet to find a solution. When I logout as one user, and sign in as a different user, the new user will appear for a split second and then be replaced by the previous user's data.
Here is my attempt to go nuclear on the cache:
onClick={() => {
client
.clearStore()
.then(() => client.resetStore())
.then(() => client.cache.reset())
.then(() => client.cache.gc())
.then(() => dispatch(logoutUser))
.then(() => history.push('/'));
}}
I've tried getting the client object from both these locations (I am using codegen):
const { data, loading, error, client } = useUserQuery();
const client = useApolloClient();
Here is my Apollo client setup:
const apolloClient = new ApolloClient({
uri: config.apiUrl,
headers: {
uri: 'http://localhost:4000/graphql',
Authorization: `Bearer ${localStorage.getItem(config.localStorage)}`,
},
cache: new InMemoryCache(),
});
When I login with a new user, I writeQuery to the cache. If I log the data coming back from the login mutation, the data is perfect, exactly what I want to write:
sendLogin({
variables: login,
update: (store, { data }) => {
store.writeQuery({
query: UserDocument,
data: { user: data?.login?.user },
});
},
})
UserDocument is generated from codegen:
export const UserDocument = gql`
query user {
user {
...UserFragment
}
}
${UserFragmentFragmentDoc}`;
Following the docs, I don't understand what my options are, I have tried writeQuery, writeFragment, and cache.modify and nothing changes. The Authentication section seems to suggest the same thing I am trying.
Seems like all I can do is force a window.location.reload() on the user which is ridiculous, there has to be a way.

Ok, part of me feels like a dumb dumb, the other thinks there's some misleading info in the docs.
despite what this link says:
const client = new ApolloClient({
cache,
uri: 'http://localhost:4000/graphql',
headers: {
authorization: localStorage.getItem('token') || '',
'client-name': 'Space Explorer [web]',
'client-version': '1.0.0',
},
...
});
These options are passed into a new HttpLink instance behind the scenes, which ApolloClient is then configured to use.
This doesn't work out of the box. Essentially what is happening is my token is being locked into the apollo provider and never updating, thus the payload that came back successfully updated my cache but then because the token still contained the old userId, the query subscriptions overwrote the new data from the new user's login. This is why refreshing worked, because it forced the client to re-render with my local storage.
The fix was pretty simple:
// headerLink :: base headers for graphql queries
const headerLink = new HttpLink({ uri: 'http://localhost:4000/graphql' });
// setAuthorizationLink :: update headers as localStorage changes
const setAuthorizationLink = setContext((request, previousContext) => {
return {
headers: {
...previousContext.headers,
Authorization: `Bearer ${localStorage.getItem(config.localStorage)}`,
},
};
});
// client :: Apollo GraphQL Client settings
const client = new ApolloClient({
uri: config.apiUrl,
link: setAuthorizationLink.concat(headerLink),
cache: new InMemoryCache(),
});
And in fact, I didn't even need to clear the cache on logout.
Hope this helps others who might be struggling in a similar way.

Related

Cypress not seeing graphql request

This seems to be a long lasting issue:
In cypress interface, my application cannot send any graphql request or receive any response. Because it is fetch type.
here is the network status in cypress:
But in normal browser, I actually have several graphql requests, like here:
I know there are already quite several discussions and workarounds, such as using an polyfill to solve this problem such as below:
https://gist.github.com/yagudaev/2ad1ef4a21a2d1cfe0e7d96afc7170bc
Cypress does not intercept GraphQL API calls
but unfortunately, they are not working in my case.
Appreciate to the help of any kinds.
p.s.: I am using cypress 8.3.0, React as the front-end, and using apollo client and apollo server for all graphql stuff.
EDIT:
samele intercept:
cy.intercept('POST', Cypress.env('backendpiUrl') + '/graphql', req => {
if (req.body.operationName === 'updateItem') {
req.alias = 'updateItemMutation';
}
});
sample cypress console:
You can see that all the requests are XHR based, no graphql's fetch request
The links are old, unfetch polyfill is no longer necessary. Since the introduction of cy.intercept(), fetch is able to be waited on, stubbed etc.
Here's the docs Working with GraphQL and an interesting atricle Smart GraphQL Stubbing in Cypress (Note route2 is an early name for intercept)
More up-to-date, posted two days ago bahmutov - todo-graphql-example
Key helper function from this package:
import {
ApolloClient,
InMemoryCache,
HttpLink,
ApolloLink,
concat,
} from '#apollo/client'
// adding custom header with the GraphQL operation name
// https://www.apollographql.com/docs/react/networking/advanced-http-networking/
const operationNameLink = new ApolloLink((operation, forward) => {
operation.setContext(({ headers }) => ({
headers: {
'x-gql-operation-name': operation.operationName,
...headers,
},
}))
return forward(operation)
})
const httpLink = new HttpLink({ uri: 'http://localhost:3000' })
export const client = new ApolloClient({
link: concat(operationNameLink, httpLink),
fetchOptions: {
mode: 'no-cors',
},
cache: new InMemoryCache(),
})
Sample test
describe('GraphQL client', () => {
// make individual GraphQL calls using the app's own client
it('gets all todos (id, title)', () => {
const query = gql`
query listTodos {
# operation name
allTodos {
# fields to pick
id
title
}
}
`
cy.wrap(
client.query({
query,
}),
)
.its('data.allTodos')
.should('have.length.gte', 2)
.its('0')
.should('deep.equal', {
id: todos[0].id,
title: todos[0].title,
__typename: 'Todo',
})
})
Please show your test and the error (or failing intercept).

Apollo Express Server on Heroku and Refresh Token Cookie on Mobile Browser

Upon visiting/refresh, the app checks for a refresh token in the cookie. If there is a valid one, an access token will be given by the Apollo Express Server. This works fine on my desktop but when using Chrome or Safari on the iPhone, the user gets sent to the login page on every refresh.
React App with Apollo Client
useEffect(() => {
fetchUser();
}, []);
const fetchUser = async () => {
const res = await fetch('https://website.com/token', {
method: 'POST',
credentials: 'include',
});
const { accessToken } = await res.json();
if (accessToken === '') {
setIsLoggedIn(false);
}
setAccessToken(accessToken);
setLoading(false);
};
Apollo Client also checks if whether the access token is valid
const authLink = setContext((_, { headers }) => {
const token = getAccessToken();
if (token) {
const { exp } = jwtDecode(token);
if (Date.now() <= exp * 1000) {
return {
headers: {
...headers,
authorization: token ? `Bearer ${token}` : '',
},
};
}
}
fetch('https://website.com/token', {
method: 'POST',
credentials: 'include',
}).then(async (res) => {
const { accessToken } = await res.json();
setAccessToken(accessToken);
return {
headers: {
...headers,
authorization: accessToken ? `Bearer ${accessToken}` : '',
},
};
});
});
const client = new ApolloClient({
link: from([authLink.concat(httpLink)]),
cache: new InMemoryCache(),
connectToDevTools: true,
});
This handles the token link on the Express server
app.use('/token', cookieParser());
app.post('/token', async (req, res) => {
const token = req.cookies.rt;
if (!token) {
return res.send({ ok: false, accessToken: '' });
}
const user = await getUser(token);
if (!user) {
return res.send({ ok: false, accessToken: '' });
}
sendRefreshToken(res, createRefreshToken(user));
return res.send({ ok: true, accessToken: createAccessToken(user) });
});
And setting of the cookie
export const sendRefreshToken = (res, token) => {
res.cookie('rt', token, {
httpOnly: true,
path: '/token',
sameSite: 'none',
secure: true,
});
};
Same site is 'none' as the front end is on Netlify.
After a day of fiddling and researching, I have found the issue, and one solution when using a custom domain.
The issue is that iOS treats sameSite 'none' as sameSite 'strict'. I thought iOS Chrome would be different than Safari but it appears not.
If you use your front-end, hosted on Netlify, you will naturally have a different domain than your Heroku app back-end. Since I am using a custom domain, and Netlify provides free SSL, half of the work is done.
The only way to set a httpOnly cookie is to set the cookie to secure. The next step would be to set sameSite to 'none' but as mentioned above, this does not work with iOS.
Setting the domain property of the cookie will also not work because the domain property concerns the scope of the cookie and not the cookie origin. If the cookie came from a different domain (Heroku backend), then the frontend (on Netlify) will not be able to use it.
By default, on Heroku, the free dyno will give you a domain like 'your-app.herokuapp.com', which is great because it also includes free SSL. However, for the cookie to work, I added my custom domain that I use with Netlify. To be clear, Netlify already uses my apex custom domain, so I am adding a subdomain to Heroku (api.domain.com). Cookies do work for across the same domain and subdomains with sameSite 'strict'.
The final issue with this is that the custom domain with Heroku will not get SSL automatically, which is why I think it is worth it to upgrade to a $7/month hobby dyno to avoid managing the SSL manually. This I think is the only solution when using a custom domain.
On the other hand, for those who have the same issue and would like a free solution, you can forgo using a custom domain and host your static front-end with the back-end on Heroku.
Hopefully this will save some time for anyone deploying the back-end and front-end separately.

How to work with both mocked graphql API and an externally served GraphQL endpoint

I'm hoping to hear some inputs from the experts here.
I'm currently working on NextJS project and my graphql is running on mocked data which is setup in another repo.
and now that the backend is built by other devs were slowly moving away from mocked data to the real ones.
They've given me an endpoint to the backend where I'm supposed to be querying data.
So the goal is to make both mocked graphql data and the real data in backend work side by side at least until we fully removed mocked data.
So far saw 2 ways of doing it, but I was looking for a way where I could still use hooks like useQuery and useMutation
Way #1
require('isomorphic-fetch');
fetch('https://graphql.api....', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ query: `
query {
popularBrands ( storefront:"bax-shop.nl", limit:10, page:1){
totalCount
items{id
logo
name
image
}
}
}`
}),
})
.then(res => res.json())
.then(res => console.log(res.data));
Way #2
const client = new ApolloClient({
uri: 'https://api.spacex.land/graphql/',
cache: new InMemoryCache()
});
async function test () {
const { data: Data } = await client.query({
query: gql`
query GetLaunches {
launchesPast(limit: 10) {
id
mission_name
launch_date_local
launch_site {
site_name_long
}
links {
article_link
video_link
mission_patch
}
rocket {
rocket_name
}
}
}
`
});
console.log(Data)
}
Pseudo code:
Query the real data first
check if its empty, if it is, query the mock data.
If both are empty, then it's really an empty result set.
You can write a wrapper around the hooks you use that does this for you so you don't have to repeat yourself in every component. When you're ready to remove the mocked data you just remove the check for the second. data set.
This is a common technique when switching to a new database.

getInitialProps in never called in NextJS

I have problem with getInitialProps method in NextJS. It is never called. This is project where I have Apollo GraphQL client for some pages and getInitialProps for other. I am not sure how to configure them correctly to work.
Apollo is working fine and fetching data as it should. Problem is that getInitialProps isn't called.
Here is my custom _app.js file
const App = ({ Component, pageProps, apollo }) => {
return (
<ApolloProvider client={apollo}>
<Component {...pageProps} />
</ApolloProvider>
)
}
const API_URL =
process.env.NODE_ENV === "development"
? "http://localhost/wordpress/index.php?graphql"
: "https://page/index.php?graphql"
export default withApollo(({ initialState }) => {
return new ApolloClient({
link: new createHttpLink({
uri: API_URL,
fetch: fetch
}),
cache: new InMemoryCache()
})
})(App, { getDataFromTree })
And here is how I call getInitialProps on page
Coupons.getInitialProps = async function() {
const res = await fetch('http://localhost:8000/data/');
const data = await res.json();
console.log(`Data fetched. Count: ${data.length}`);
return {
shows: data.map(entry => entry.show)
};
};
Also. Pages where I have Apollo fetching data doesn't need to call this REST API. Apollo pages and REST pages are totally different
This problem was fixed by following documentation on https://github.com/zeit/next.js/tree/canary/examples/with-apollo
Thing is that I wrapped whole _app in Apollo provider and right way is to wrap only pages that need Apollo in it.
Other that need getInitialProps should remain as is and call REST API in them.

Use Apollo Client or Isomorphic Fetch with GraphiQL

I am trying to integrate the GraphiQL IDE into my website and am wondering if I can get some advice on whether I would be best using the Apollo Client that the rest of the site uses or using Isomorphic Fetch as recommended in the documentation.
If I use the Apollo Client then I only have one connection to worry about and don't have to think about ensuring authentication is correct but the code is more complex.
I have this code working for the fetcher function, but so far it only works with queries and to my understanding would need a fair amount of work to work with mutations as well.
graphQlFetcher = (params) => {
return this.props.client.query({
query: gql`
${params.query}
`
}).then(function(result) {
return result;
});
}
Alternatively there is the isomorphic fetch approach, but for this to work I need to get the authentication token first and I am not good enough with promises to make this work. Not working code:
import { Auth } from 'aws-amplify';
getToken = async () => {
const session = await Auth.currentSession();
return session.accessToken.jwtToken;
}
graphQLFetcher = (graphQLParams) => {
return getToken().then(function(token) {
fetch(window.location.origin + '/graphql', {
method: 'post',
headers: {
'Content-Type': 'application/json',
"Authorization": token
},
body: JSON.stringify(graphQLParams),
}).then(response => response.json());
})
}
Appreciate that there are two possible ways to solve this problem and that it is as much a design question as a technical one but hoping that someone can help me out.
The first one is fine, but you have some excess syntax on there. This is what I use:
params => client.query({ ...params, query: gql(params.query) });

Resources