Skip to content
New issue

Have a question about this project? # for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “#”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? # to your account

ApolloError: Query failed upstream when using Apollo Client in Next.js app #372

Closed
naimulemon opened this issue Oct 12, 2024 · 2 comments
Closed

Comments

@naimulemon
Copy link

Description:
I am encountering an ApolloError: Query failed upstream when using Apollo Client in my Next.js 14 app. The issue occurs when attempting to execute a query using PreloadQuery. Here’s the error stack trace:

⨯ ApolloError: Query failed upstream.
    at new Promise (<anonymous>)
digest: "2315169713"
Cause: Error: Query failed upstream.

Code Snippet:

"use client";
import { ApolloLink, HttpLink } from "@apollo/client";
import {
  ApolloNextAppProvider,
  SSRMultipartLink,
  InMemoryCache,
  ApolloClient,
} from "@apollo/experimental-nextjs-app-support";

function makeClient(cookies: string | undefined) {
  const httpLink = new HttpLink({
    uri: "http://localhost:8080/graphql",
    credentials: "include",
    headers: {
      Cookie: `jwt=${cookies}`,
    },
  });

  return new ApolloClient({
    cache: new InMemoryCache(),
    credentials: "include",
    connectToDevTools: true,
    defaultOptions: {
      query: {
        fetchPolicy: "cache-first",
        notifyOnNetworkStatusChange: true,
      },
      mutate: {
        fetchPolicy: "network-only",
      },
    },
    link:
      typeof window === "undefined"
        ? ApolloLink.from([
            new SSRMultipartLink({
              stripDefer: true,
            }),
            httpLink,
          ])
        : httpLink,
  });
}

export function ApolloWrapper({
  children,
  token,
}: {
  children: React.ReactNode;
  token: string | undefined;
}) {
  return (
    <ApolloNextAppProvider makeClient={() => makeClient(token)}>
      {children}
    </ApolloNextAppProvider>
  );
}

The issue happens when querying data using this component:

import { ApolloWrapper } from "@/lib/apollo-wrapper-with-token";
import { PreloadQuery, CategoriesDocument } from "@/__generated__/graphql";
import { ErrorBoundary } from "react-error-boundary";
import React, { Suspense } from "react";
import CategoriesDemo from "./components/categories";
import { cookies } from "next/headers";

const DemoPage: React.FC = async () => {
  const cookie = cookies().get("jwt")?.value;

  return (
    <div>
      <h1>Welcome to the Demo Page</h1>
      <ApolloWrapper token={cookie}>
        <PreloadQuery
          query={CategoriesDocument}
          variables={{ categoryFilter: {} }}
        >
          <ErrorBoundary fallback={<div>Something went wrong</div>}>
            <Suspense fallback={<div>Loading...</div>}>
              <CategoriesDemo />
            </Suspense>
          </ErrorBoundary>
        </PreloadQuery>
      </ApolloWrapper>
    </div>
  );
};

The main issue happend when I use preload query with suspense query.

"use client";
import { useCategoriesSuspenseQuery } from "@/__generated__/graphql";
import React from "react";

const CategoriesDemo = () => {
  const { data, error } = useCategoriesSuspenseQuery({
    variables: {
      categoryFilter: {},
    },
    fetchPolicy: "cache-first",
  });
  if (error) {
    return <div>Error {error.message}</div>;
  }

  return <pre>{JSON.stringify(data, null, 2)}</pre>;
};

export default CategoriesDemo;

What I’ve Tried:

  • Verified the GraphQL endpoint (http://localhost:8080/graphql) is accessible and working.
  • Ensured that the correct headers, including cookies, are sent with the request.

Expected Behavior:
The query should succeed and return the appropriate data without any errors.

Actual Behavior:
The query fails with the error ApolloError: Query failed upstream.

Environment:

  • Next.js version: 14
  • Apollo Client: @apollo/client and @apollo/experimental-nextjs-app-support
  • Node.js: v18.x
  • Backend: Nest.js with Apollo GraphQL

Additional Information:

  • The error seems to occur specifically when using PreloadQuery with Apollo’s new Next.js App Router integration.
  • The server-side Apollo Client is wrapped with SSRMultipartLink.
@naimulemon
Copy link
Author

Description: I am encountering an ApolloError: Query failed upstream when using Apollo Client in my Next.js 14 app. The issue occurs when attempting to execute a query using PreloadQuery. Here’s the error stack trace:

⨯ ApolloError: Query failed upstream.
    at new Promise (<anonymous>)
digest: "2315169713"
Cause: Error: Query failed upstream.

Code Snippet:

"use client";
import { ApolloLink, HttpLink } from "@apollo/client";
import {
  ApolloNextAppProvider,
  SSRMultipartLink,
  InMemoryCache,
  ApolloClient,
} from "@apollo/experimental-nextjs-app-support";

function makeClient(cookies: string | undefined) {
  const httpLink = new HttpLink({
    uri: "http://localhost:8080/graphql",
    credentials: "include",
    headers: {
      Cookie: `jwt=${cookies}`,
    },
  });

  return new ApolloClient({
    cache: new InMemoryCache(),
    credentials: "include",
    connectToDevTools: true,
    defaultOptions: {
      query: {
        fetchPolicy: "cache-first",
        notifyOnNetworkStatusChange: true,
      },
      mutate: {
        fetchPolicy: "network-only",
      },
    },
    link:
      typeof window === "undefined"
        ? ApolloLink.from([
            new SSRMultipartLink({
              stripDefer: true,
            }),
            httpLink,
          ])
        : httpLink,
  });
}

export function ApolloWrapper({
  children,
  token,
}: {
  children: React.ReactNode;
  token: string | undefined;
}) {
  return (
    <ApolloNextAppProvider makeClient={() => makeClient(token)}>
      {children}
    </ApolloNextAppProvider>
  );
}

The issue happens when querying data using this component:

import { ApolloWrapper } from "@/lib/apollo-wrapper-with-token";
import { PreloadQuery, CategoriesDocument } from "@/__generated__/graphql";
import { ErrorBoundary } from "react-error-boundary";
import React, { Suspense } from "react";
import CategoriesDemo from "./components/categories";
import { cookies } from "next/headers";

const DemoPage: React.FC = async () => {
  const cookie = cookies().get("jwt")?.value;

  return (
    <div>
      <h1>Welcome to the Demo Page</h1>
      <ApolloWrapper token={cookie}>
        <PreloadQuery
          query={CategoriesDocument}
          variables={{ categoryFilter: {} }}
        >
          <ErrorBoundary fallback={<div>Something went wrong</div>}>
            <Suspense fallback={<div>Loading...</div>}>
              <CategoriesDemo />
            </Suspense>
          </ErrorBoundary>
        </PreloadQuery>
      </ApolloWrapper>
    </div>
  );
};

The main issue happend when I use preload query with suspense query.

"use client";
import { useCategoriesSuspenseQuery } from "@/__generated__/graphql";
import React from "react";

const CategoriesDemo = () => {
  const { data, error } = useCategoriesSuspenseQuery({
    variables: {
      categoryFilter: {},
    },
    fetchPolicy: "cache-first",
  });
  if (error) {
    return <div>Error {error.message}</div>;
  }

  return <pre>{JSON.stringify(data, null, 2)}</pre>;
};

export default CategoriesDemo;

From React Unhandled runtime

react-dom.development.js:17497  Uncaught Error: Query failed upstream.
    at updateDehydratedSuspenseComponent (react-dom.development.js:17497:1)
    at updateSuspenseComponent (react-dom.development.js:17193:1)
    at beginWork$1 (react-dom.development.js:18509:1)
    at beginWork (react-dom.development.js:26927:1)
    at performUnitOfWork (react-dom.development.js:25748:1)
    at workLoopSync (react-dom.development.js:25464:1)
    at renderRootSync (react-dom.development.js:25419:1)
    at performConcurrentWorkOnRoot (react-dom.development.js:24504:1)
    at workLoop (scheduler.development.js:256:1)
    at flushWork (scheduler.development.js:225:1)
    at MessagePort.performWorkUntilDeadline (scheduler.development.js:534:1)

What I’ve Tried:

  • Verified the GraphQL endpoint (http://localhost:8080/graphql) is accessible and working.
  • Ensured that the correct headers, including cookies, are sent with the request.

Expected Behavior: The query should succeed and return the appropriate data without any errors.

Actual Behavior: The query fails with the error ApolloError: Query failed upstream.

Environment:

  • Next.js version: 14
  • Apollo Client: @apollo/client and @apollo/experimental-nextjs-app-support
  • Node.js: v18.x
  • Backend: Nest.js with Apollo GraphQL

Additional Information:

  • The error seems to occur specifically when using PreloadQuery with Apollo’s new Next.js App Router integration.
  • The server-side Apollo Client is wrapped with SSRMultipartLink.

Copy link

Do you have any feedback for the maintainers? Please tell us by taking a one-minute survey. Your responses will help us understand Apollo Client usage and allow us to serve you better.

# for free to join this conversation on GitHub. Already have an account? # to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant