I'm a bit confused on how to structure my React/GraphQL (Apollo) app when no connection should be made until the user authenticates/logs in.
Currently I have this:
class App extends Component {
render() {
return (
<ApolloProvider client={client}>
<Provider store={store}>
<Router>
<div>
<ul>
<li><Link to="/">Home</Link></li>
<li><Link to="/login">Log In</Link></li>
<li><Link to="/signup">Sign Up</Link></li>
</ul>
<AuthenticatedRoute exact path="/" component={HomePage} />
<Route path="/login" component={LoginPage} />
<Route path="/signup" component={SignupPage} />
</div>
</Router>
</Provider>
</ApolloProvider>
);
}
}
Here's the creation of the network interface:
const networkInterface = createNetworkInterface({
uri: process.env.NODE_ENV === 'development'
? 'http://localhost:3000/graphql'
: 'TBD',
});
networkInterface.use([
{
applyMiddleware(req, next) {
if (!req.options.headers) {
req.options.headers = {}; // Create the header object if needed.
}
getUserSession()
.then(session => {
// get the authentication token from local storage if it exists
// ID token!
req.options.headers.authorization = session
.getIdToken()
.getJwtToken();
})
.catch(err => {
console.error('oh, this is bad');
})
.then(next);
},
},
]);
How do I organize this so that the Apollo client is only initialized and set up once, and only after the user has authenticated?
I'm wondering if I could use withApollo to somehow access the client directly and complete the GraphQL auth & connection that way.
Idea 2
Use Redux to track user state, wrap App
with connect
. When the user authenticates, this triggers a Redux state change which triggers App
's componentDidUpdate
which could create the network interface for Apollo, causing a re-render in App
which would pass an authorized client
into <ApolloProvider client={client}>
.
I use ApolloClient example http://dev.apollodata.com/react/auth.html#Header
the block
applyMiddleware
will always run before fetching to GraphQL server, so you just need to setlocalStorage
when login and delete when logout.I typically listen for a "isLoggedIn" field to be set to true from redux. When it's set to true, I render the full app and add the authentication header so that the function adds the JWT token to all future requests.