Fix authorisation problem in nextjs strapi apollo graphql app
Budget: $2 – $8 USD
Hi! I am building a website using nextjs strapi apollo graphql, next-with-appollo package app, authenticating users with jwt the problem is I could not find the right way to put headers in config.
I am going to get user from context and use it in header in nextjs strapi apollo graphql project User is accessable in App function but outside its giving above error.
import "../styles/globals.css";
import Layout from "../components/Layout";
import { Provider } from "../context/AppContext";
import Cookies from "js-cookie";
import withApollo from "next-with-apollo";
import { BACKEND_URL } from "../helpers";
import React, { useContext } from "react";
import { AppContext } from "../context/AppContext";
import { ApolloClient, ApolloProvider, InMemoryCache } from "@apollo/client";
const { user } = useContext(AppContext);
console.log("user from context in _app", user);
function App({ Component, pageProps, apollo }) {
return (
<Provider>
<ApolloProvider client={apollo}>
<Layout>
<Component {...pageProps} />
</Layout>
</ApolloProvider>
</Provider>
);
}
export default withApollo(({ initialState, headers }) => {
return new ApolloClient({
uri: `${BACKEND_URL}/graphql`,
cache: new InMemoryCache().restore(initialState || {}),
...(user && {
headers: {
authorization: `Bearer ${user.token}`,
},
}),
});
})(App);
I am going to get user from context and use it in header in nextjs strapi apollo graphql project User is accessable in App function but outside its giving above error.
import "../styles/globals.css";
import Layout from "../components/Layout";
import { Provider } from "../context/AppContext";
import Cookies from "js-cookie";
import withApollo from "next-with-apollo";
import { BACKEND_URL } from "../helpers";
import React, { useContext } from "react";
import { AppContext } from "../context/AppContext";
import { ApolloClient, ApolloProvider, InMemoryCache } from "@apollo/client";
const { user } = useContext(AppContext);
console.log("user from context in _app", user);
function App({ Component, pageProps, apollo }) {
return (
<Provider>
<ApolloProvider client={apollo}>
<Layout>
<Component {...pageProps} />
</Layout>
</ApolloProvider>
</Provider>
);
}
export default withApollo(({ initialState, headers }) => {
return new ApolloClient({
uri: `${BACKEND_URL}/graphql`,
cache: new InMemoryCache().restore(initialState || {}),
...(user && {
headers: {
authorization: `Bearer ${user.token}`,
},
}),
});
})(App);