Skip to main content

GraphQL Authentication

Here's an example using simple cookie auth:

schema/endpoint.ts
import { GQLEndpoint } from '@data-client/graphql';

class CookieGQLEndpoint extends GQLEndpoint<any> {
getRequestInit(variables: any): RequestInit {
return {
...super.getRequestInit(variables),
credentials: 'same-origin',
};
}
}

export const gql = new CookieGQLEndpoint(
'https://nosy-baritone.glitch.me',
);
export default gql;

Access Tokens​

Here we'll keep the access token in a module variable and send it in a header. Endpoints made with gql.query() and gql.mutation() copy gql when they are created, so a value set on gql afterward would not reach them; a module variable is read on every request.

schema/endpoint.ts
import { GQLEndpoint } from '@data-client/graphql';

let accessToken = '';
export function setAccessToken(token: string) {
accessToken = token;
}

export const gql = new GQLEndpoint('https://nosy-baritone.glitch.me', {
getHeaders(headers: HeadersInit): HeadersInit {
return {
...headers,
'Access-Token': accessToken,
};
},
});
export default gql;

Then be sure to set the access token upon login:

import { setAccessToken } from 'schema/endpoint';

function Auth() {
const handleLogin = useCallback(
async e => {
const { accessToken } = await login(new FormData(e.target));
// success!
setAccessToken(accessToken);
},
[login],
);

return <AuthForm onSubmit={handleLogin} />;
}

401 Logout Handling​

In case a users authorization expires, the server will typically responsd to indicate as such. The standard way of doing this is with a 401. LogoutManager can be used to easily trigger any de-authorization cleanup.