So my problems is how would I get the localStorage jwt token that i've been using to pass on the header for my separate apollo graphql server
Below is how I try to setup the token store/index.js
import Vuex from "vuex";
import { Auth, Login } from "~/apollo/gql/Auth.gql";
import Cookie from "js-cookie";
export const state = () => ({
auth: null,
token: ""
});
export const mutations = {
SET_TOKEN(state, data) {
state.token = data;
}
};
export const actions = {
async nuxtServerInit(store, context) {
let client = context.app.apolloProvider.defaultClient;
let { data } = await client.query({
query: Auth,
fetchPolicy: "network-only"
});
const token = Cookie.get("token");
console.log(token);
console.log(context, store, data);
},
async login({ commit }, data) {
const client = this.app.apolloProvider.defaultClient;
const { data: val } = await client.mutate({
mutation: Login,
variables: {
data
}
});
localStorage.setItem("token", val.result.token);
Cookie.set("token", val.result.token);
const token = Cookie.get("token");
console.log(token);
commit("SET_TOKEN", val.result.token);
}
};
I'll use my login function to send a mutation request on my api server then get that token back
It works when i Login but when on the case of reloading the page
the token is not set on nuxtServerInit so what I wanted to do is how do I store the token somehow on the request object of the nuxt server so whenever I try to check the user if he/she is authenticated I will just set the token on startup on the Token state
Also tried the cookie library
but seems I don't get the idea how cookie works maybe give me a simple point of view of how cookie session work?
I tried to find the session property on the request object but it's not there
this some part of the config for apollo-client
// auth token
let getToken = () =>
process.server ? ctx.req.session : localStorage.getItem("token");
// middleware
const middlewareLink = new ApolloLink((operation, forward) => {
if (process.server) console.log(ctx);
operation.setContext({
headers: {
authorization: `Bearer ${getToken()}`
}
});
return forward(operation);
});
const wsLink = process.client
? new WebSocketLink({
uri: process.env.SUBSCRIPTIONS_ENDPOINT,
options: {
reconnect: true,
connectionParams: () => {
const token = getToken();
return {
Authorization: token ? `Bearer ${token}` : null
};
}
}
})
: "";
<!--cmty--><!--cmty_prevent_hook--><div align="right"><sub><em>This question is available on <a href="https://nuxtjs.cmty.io">Nuxt.js</a> community (<a href="https://nuxtjs.cmty.io/nuxt/nuxt.js/issues/c2373">#c2373</a>)</em></sub></div>