'Document is undefined when using apollo query with next.js getServerSideProps
I am trying to use getServerSideProps
to fetch a query every time this component is rendered using apollo
and next.js
export async function getServerSideProps(context) {
const { data } = await client.query({
query: GET_AUTHED_USER
})
return {
props: { user: data.getAuthedUser },
}
}
const Profile = ({ user }) => {
const router = useRouter();
// const [state, setState] = useState(JSON.parse(router.query.currentUser));
const [state, setState] = useState(user);
console.log(state)
...
APOLLO CONFIG
import { ApolloClient, InMemoryCache, ApolloLink } from '@apollo/client';
import { getCookie } from './utils/functions';
import { setContext } from '@apollo/client/link/context';
import { createUploadLink } from 'apollo-upload-client';
const authLink = setContext((_, { headers }) => {
// get the authentication token from storage if it exists
const token = getCookie('JWT');
// return the headers to the context so httpLink can read them
return {
headers: {
...headers,
authorization: token ? token : '',
}
}
});
const httpLink = createUploadLink({
uri: 'http://localhost:5000/graphql',
});
const client = new ApolloClient({
uri: 'http://localhost:5000/graphql',
cache: new InMemoryCache(),
link: ApolloLink.from([authLink, httpLink])
});
export default client;
currently, when visiting the /profile
page I receive the error:
Server Error
Error: document is not defined
Does anyone have any insight on how to resolve this or suggest a valid work around?
Solution 1:[1]
appolo/client is a client side library. getServersideProps execute in server side. document doesn't exist in server side. It will only work within client side.
Workaround 1:
You can use swr. swr is for client side data fetch. so you don't need getServerSideProps.
Workaround 2:
You can use apollo-server. Then you can call apollo-server function in getServerSideProps as apollo-server is for server side calling.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Tamzid Ahmed |