Reputation: 1309
I am learning GraphQL and Next.js through a Udemy Course and the author uses ApolloClient from apollo-boost package. But @apollo/client package is the new one and I started using that instead.
using apollo-boost's ApolloClient the author sets the credentials for each request like below:
new ApolloClient({
request: operation => {
operation.setContext({
fetchOptions: {
credentials: 'include'
},
headers
})
},
uri: process.env.BASE_URL,
cache: new InMemoryCache().restore(initialState || {})
})
This is not working for me as request is not present in @apollo/client's ApolloClient. So I tried like below:
const link = new HttpLink({ uri: "http://localhost:3000/graphql", credentials: 'include' });
new ApolloClient({
cache: new InMemoryCache().restore(initialState || { }),
link,
})
But the credentials are not working for each request. I am not getting user information. I am using passport which is storing logged in user info in cookies. Below is the index.js file for configuring passport:
const config = require('../config/dev');
const sessison = require('express-session');
const passport = require('passport');
exports.init = (server, db) => {
require('./passport').init(passport);
const sess = {
name: 'portfolio-session',
secret: config.SESSION_SECRET,
cookie: { maxAge: 2 * 60 * 60 * 100},
resave: false,
saveUninitialized: false,
store: db.initSessionStore()
}
server.use(sessison(sess));
server.use(passport.initialize());
server.use(passport.session());
}
Can somebody help with code to add authentication to ApolloClient?
Thanks :)
Upvotes: 0
Views: 3330
Reputation: 1756
From the looks of it you are not actually passing the header bearing the token in your example. Take the headers incoming from the first author's example:
[...]
fetchOptions: {
credentials: 'include'
},
headers // <- this one
})
},
[...]
Add it to the request like you were trying to do:
const link = new HttpLink({
uri: "http://localhost:3000/graphql",
headers // <-- pass it here, should contain something along these lines: { Authorization: `Bearer ${token}` } or w/e
});
const client = new ApolloClient({
cache: new InMemoryCache().restore(initialState || { }),
link,
});
Upvotes: 1