NextJs: getServerSideProps is not working with Apollo: fetch failed - next.js

I'm trying to generate the page from the server side page on Next.js, But I'm having a problem with it, so I have created an Apollo instance and I'm importing a Query from my queries, and I pass the variable as I do on useQuery from apollo on the client, because I don't know another way to do that, also how to handle errors on this?
Here are my getServerSideProps:
export async function getServerSideProps(context) {
const slug = context.params.slug;
const data = await Static.query({
query: LANDING,
variables: { slug },
});
return {
props: {
data: data,
},
};
}
Here is my query:
import gql from "graphql-tag";
export const CATEGORIES = gql`
query CategoriesView {
CategoriesView {
_id
Name
Description
Icon
}
}
`;
Here is my Client:
import {
ApolloClient,
HttpLink,
ApolloLink,
InMemoryCache,
} from "#apollo/client";
const uri = "http://localhost:3000/api"
const httpLink = new HttpLink({uri});
export const Apollo = new ApolloClient({
ssr: typeof window === "undefined" ? true : false,
cache: new InMemoryCache(),
link: ApolloLink.from([httpLink]),
});
But I get this error: failed to fetch
Here is a screenshot of it:

Here is my example, working in my case.
import { useSubscription, useQuery, gql } from "#apollo/client";
import { serverSideTranslations } from "next-i18next/serverSideTranslations";
//your query here ; first check if your query works (use your playground)
const QUERY = gql`
query {
customers{
data{
attributes{
firstname
lastname
location
phone
createdAt
}
}
}
}
`;
const Page = () => {
//apollo function
const { data, loading, error } = useQuery(QUERY);
if (loading) return <div>Loading...</div>
if (error) return <div>Failed to load!</div>
return (
<>
{JSON.stringify(data)}
</>
)
};
//can do with staticProps, serverProps, etc. Below just an example - delete if not needed
export async function getStaticProps({ locale }) {
return {
props: {
...(await serverSideTranslations(locale, ["common"])),
},
};
}
export default Page;
I am not sure if you can put gql query in getServerSideProps because apollo creates some sort of "cache" for your queries.
And check #apollo/client library

Related

Client query is not a function graphql nextjs

I'm trying to call my graphql in SSR with nextjs. But when I try to make my queries, I have the following error:
Server Error
TypeError: apollo_client__WEBPACK_IMPORTED_MODULE_2___default(...).query is not a function
This is my current file.
import client from 'apollo-client';
import { GetServerSideProps } from 'next';
export const getServerSideProps: GetServerSideProps = async context => {
const { id } = context.params;
const { data } = await client.query({
query: GET_ORDER_BY_NUMBER,
variables: {
orderNumber: id
}
});
const order: IOrder = data.getOrderByNumber[0];
return {
props: {
order
}
};
}
and for the apollo-client file, I have this:
import { ApolloClient, createHttpLink, InMemoryCache } from '#apollo/client';
const httpLink = createHttpLink({
uri: `/api/graphql`
});
const client = new ApolloClient({
link: httpLink,
cache: new InMemoryCache()
});
export default client;

Apollo client can't query in Nextjs getServerSideProps via SchemaLink

Apollo client fails to do query when initialized with SchemaLink (nexus) instead of HttpLink. I get this error Cannot set properties of undefined (setting 'select')
function createIsomorphLink() {
if (typeof window === 'undefined') {
const { SchemaLink } = require('#apollo/client/link/schema')
const { schema } = require('./nexusSchema')
return new SchemaLink({ schema })
} else {
const { HttpLink } = require('#apollo/client/link/http')
return new HttpLink({
uri: '/api/graphql',
credentials: 'same-origin',
})
}
}
function createApolloClient() {
return new ApolloClient({
ssrMode: typeof window === 'undefined',
link: from([errorLink, createIsomorphLink()]),
cache: new InMemoryCache(),
})
}
Here's my getServerSideProps. I initialize apollo client and use apolloClient.query(...)
export const getServerSideProps = async ({ params }) => {
const id = params.id
const apolloClient = initializeApollo()
// Here's where the error occurs
const { data } = await apolloClient.query({
query: gql`
query findUniquePage($id: String!) {
findUniquePage(where: { id: $id }) {
title
type
content
isPublished
}
}
`,
variables: { id },
})
// ...snippet..
}
I tried creating simple 'hello' query with string response, so that there was no select part. But error stayed the same.
export const getServerSideProps = async () => {
const apolloClient = initializeApollo()
const { data } = await apolloClient.query({
query: gql`query hello { hello }`,
})
return {
props: {},
}
}
My apollo client version is 3.7.0. The latest is 3.7.1 but by CHANGELOG there seems to be nothing that addresses my issue. Probably, the problem is how apollo client requests my api via SchemaLink, or how my api parses that request (apollo server + code first nexus). Because when I replaced SchemaLink with HttpLink, code worked fine. But I kinda want to keep the SchemaLink. Any advice?

How to define dataSources with #apollo/client and NextJS?

I'm trying to use NextJS with Apollo, but I can't understand where should I insert my dataSources, so I'd be able to access it through context in my resolvers (as stated in the docs).
Here's my apollo.ts (the same from NextJS with-typescript-graphql example):
import { IncomingMessage, ServerResponse } from 'http'
import { useMemo } from 'react'
import {
ApolloClient,
InMemoryCache,
NormalizedCacheObject,
} from '#apollo/client'
import resolvers from './resolvers'
import typeDefs from './schema'
let apolloClient: ApolloClient<NormalizedCacheObject> | undefined
export type ResolverContext = {
req?: IncomingMessage
res?: ServerResponse
}
function createIsomorphLink(context: ResolverContext = {}) {
if (typeof window === 'undefined') {
const { SchemaLink } = require('#apollo/client/link/schema')
const { makeExecutableSchema } = require('#graphql-tools/schema')
const schema = makeExecutableSchema({
typeDefs,
resolvers,
})
return new SchemaLink({ schema, context })
} else {
const { HttpLink } = require('#apollo/client')
return new HttpLink({
uri: '/api/graphql',
credentials: 'same-origin',
})
}
}
function createApolloClient(context?: ResolverContext) {
return new ApolloClient({
ssrMode: typeof window === 'undefined',
link: createIsomorphLink(context),
cache: new InMemoryCache(),
})
}
export function initializeApollo(
initialState: any = null,
// Pages with Next.js data fetching methods, like `getStaticProps`, can send
// a custom context which will be used by `SchemaLink` to server render pages
context?: ResolverContext
) {
const _apolloClient = apolloClient ?? createApolloClient(context)
// If your page has Next.js data fetching methods that use Apollo Client, the initial state
// get hydrated here
if (initialState) {
_apolloClient.cache.restore(initialState)
}
// For SSG and SSR always create a new Apollo Client
if (typeof window === 'undefined') return _apolloClient
// Create the Apollo Client once in the client
if (!apolloClient) apolloClient = _apolloClient
return _apolloClient
}
export function useApollo(initialState: any) {
const store = useMemo(() => initializeApollo(initialState), [initialState])
return store
}
I tried to put it alonside with typeDefs in the parameters for makeExecutable, but it's still undefined when I try to use it.
My confusion is because this setup doesn't use the new ApolloServer() constructor, as the example in the docs and I can't find some docs which relates to my setup.

How to initialize router before rendering anything in Nextjs?

I'm using react-query, when I get the id from the url and try to call it inside getSubject, it passes an undefined value http://localhost:3000/api/subject/undefined
but when I click a link from another component to get in this subject component it works but if refresh the page it does not work.
const router = useRouter()
const { id } = router.query
const { data } = useQuery('subjects', async () => await getSubject(id))
return value...
}
You should use getServerSideProps in this case. It has access to query params. On top of that you can prefetch data on the server side too.
export interface PageProps {
id: string;
}
export function Page({ id }: PageProps ) {
const { data } = useQuery('subjects', async () => await getSubject(id))
}
export const getServerSideProps: GetServerSideProps<PageProps > = async ({
params,
}) => {
const { id } = params;
return {
props: {
id,
},
};
};
If you still want to use router, you can wait for router.isReady flag. When it is true, query params should be parsed.

App working locally but not on production: TypeError: Cannot read property 'titulo_categoria' of undefined

I'm trying to deploy an app using Prismic as CMS and everything works perfectly locally, but once I deploy to vercel I get the error:
19:09:51.850 | TypeError: Cannot read property 'titulo_categoria' of undefined
There seems to be something wrong when it tries to get the data from Prismic.
My code is the following:
import {getAllCategorias, getCategory2} from '../../lib/api';
export default function Index({cat}) {
return <>{cat.titulo_categoria[0].text}</>;
}
export async function getStaticProps({params}) {
const data = await getCategory2(params.slug);
return {
props: {
cat: data?.categorias ?? null,
},
};
}
export async function getStaticPaths() {
const allPosts = await getAllCategorias();
return {
paths: allPosts?.map(({node}) => `/test/${node._meta.uid}`) || [],
fallback: true,
};
}
And the API code that gets data from Prismic is:
import Prismic from 'prismic-javascript';
const REPOSITORY = process.env.PRISMIC_REPOSITORY_NAME;
const REF_API_URL = `https://${REPOSITORY}.prismic.io/api/v2`;
const GRAPHQL_API_URL = `https://${REPOSITORY}.prismic.io/graphql`;
// export const API_URL = 'https://your-repo-name.cdn.prismic.io/api/v2'
export const API_TOKEN = process.env.PRISMIC_API_TOKEN;
export const API_LOCALE = process.env.PRISMIC_REPOSITORY_LOCALE;
export const PrismicClient = Prismic.client(REF_API_URL, {
accessToken: API_TOKEN,
});
async function fetchAPI(query, {previewData, variables} = {}) {
const prismicAPI = await PrismicClient.getApi();
const res = await fetch(
`${GRAPHQL_API_URL}?query=${query}&variables=${JSON.stringify(variables)}`,
{
headers: {
'Prismic-Ref': previewData?.ref || prismicAPI.masterRef.ref,
'Content-Type': 'application/json',
'Accept-Language': API_LOCALE,
Authorization: `Token ${API_TOKEN}`,
},
}
);
if (res.status !== 200) {
console.log(await res.text());
throw new Error('Failed to fetch API');
}
const json = await res.json();
if (json.errors) {
console.error(json.errors);
throw new Error('Failed to fetch API');
}
return json.data;
}
export async function getCategory2(slug) {
const data = await fetchAPI(
`
query CategoryBySlug($slug: String!, $lang: String!) {
categorias(uid: $slug, lang: $lang) {
titulo_categoria
_meta {
uid
}
}
}
`,
{
variables: {
slug,
lang: API_LOCALE,
},
}
);
return data;
}
Any idea what's wrong with this? I been trying to figure it out for the whole day without any luck
Perhaps you already checked that, but since you mentioned everything works locally and not on Vercel are you sure your environment variables are set there? Especially PRISMIC_API_TOKEN since it appears you're relying on it to query the API?
Also I'm a bit worried about that part of the code:
props: {
cat: data?.categorias ?? null,
}
...where you might be sending a null value to your Index component resulting in your error, I'd try that instead:
props: {
cat: data?.categorias ?? {},
}
...plus using the safe navigation operator (?.) on the Index component?
Let me know how it goes!

Resources