Signout when Apollo GraphQL token is invalid or it has expired #889
Unanswered
JavierMartinz
asked this question in
Help
Replies: 1 comment
-
I’m thinking about it too. Haven’t tested it but I assume it could work something like this: function createErrorLink(errorCallback) {
return onError(({ graphQLErrors }) => {
if (graphQLErrors?.[0]?.message === 'Unauthenticated.') {
errorCallback(/* params */)
}
});
}
function createApolloClient(session, errorCallback) {
return new ApolloClient({
cache: new InMemoryCache(),
ssrMode: typeof window === 'undefined',
link: from([
createErrorLink(errorCallback),
createUploadLink({
uri: GRAPHQL_URI,
credentials: 'same-origin',
headers: { Authorization: session?.accessToken ? `Bearer ${session.accessToken}` : '' },
}),
]),
});
} Then you can use this on client: // You can also modify `useApollo` to take 2 arguments and construct the handler in component
export function useApollo(session) {
const dispatch = useDispatch()
const handleError = () => dispatch(logout()) // Logout action clears user state & calls signOut
const store = useMemo(() => createApolloClient(session, handleError), [initialState]);
return store;
} On server, it would look like this: export async function getServerSideProps(ctx) {
const session = {}
const apolloClient = initializeApollo(session,() => {
ctx.res.cookies.set(NEXT_AUTH_COOKIE_NAME, { maxAge: Date.now() });
});
…
} |
Beta Was this translation helpful? Give feedback.
0 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
-
Your question
What is the recommended way to
signout
and clear the Access-Token from GraphQL if the token is invalid or it has expired?What are you trying to do
What would it be the best way to clear the NextAuth.js session when trying to hit the backend (Apollo GraphQL) and it returns a
401
because the token has expired or is invalid?I thought about an
errorLink
andsignout
, but as far as I knowsignout
cannot be used server side atgetServerSideProps
, but only client-side.What is the recommended way to do so? Is there any other way to implement a middleware to take care of that scenario?
This would be the proof of concept of the
errorLink
I'm trying to implement, the code is caught in that if but I can't usesignOut()
as it's only available client-side.Feedback
https://next-auth.js.org/getting-started/client#signout
Beta Was this translation helpful? Give feedback.
All reactions