Skip to content
This repository has been archived by the owner on Nov 10, 2024. It is now read-only.

Latest commit

 

History

History
41 lines (26 loc) · 1.74 KB

til-apolloclient-authentication-graphql.org

File metadata and controls

41 lines (26 loc) · 1.74 KB

TIL: ApolloClient Authentication (graphql)

WARNING: This is old and likely obsolete.

  • Time-stamp: <2020-03-23 05:01:13 tamara>
  • original date: 2017-07-22 02:19
  • keywords: webdev, graphql, react, apollo-client

Continuing to work on the GraphQL Client and Server project at work, today I learned how to authenticate using ApolloClient.

IMPORTANT NOTE: the example here is for version 1 of ApolloClient, version 2 does this in a very different manner.

(Note: there’s lots I’ve learned the past couple of weeks, but I haven’t gotten to write everything up. This is just today’s big learning.)

It turns out that authenticating is rather easy when you’re working in a same origin situation, i.e., the React Apollo client is calling an endpoint from the same domain the React client was downloaded from.

The Authentication page for the React Apollo client is very straight-forward in it’s explanation. Since the application is using Cookies to keep the authentication for the app, the following code works well:

WARNING WARNING WARNING: VERSION 1 CLIENT:

import { ApolloClient, createNetworkInterface } from 'react-apollo';

const networkInterface = createNetworkInterface({
  uri: '/graphql',
  opts: {
    credentials: 'same-origin'
  }
})

const client = new ApolloClient({
  networkInterface
});

export default client

The essential bit is tne credentials: 'same-origin' option. ApolloClient knows how to handle these and builds the request header with the appropriate cookies.

I’m sort of embarassed how long it took me to figure out that this was the solution to the problem I was having, since all I was seeing was an Internal Server Error.