apollo-client-devtools icon indicating copy to clipboard operation
apollo-client-devtools copied to clipboard

Dev tools cannot connect to my project with Apollo client and Next.js

Open drujbanjo opened this issue 5 months ago • 9 comments

When refreshing the Next.js page, Apollo client dev tools cannot connect to my Apollo client. I have connectToDevTools enabled in the client.

Link to Reproduction

import { ApolloClient, InMemoryCache } from '@apollo/client'

export const client = new ApolloClient({
	uri: 'https://graphqlplaceholder.vercel.app/graphql',
	cache: new InMemoryCache(),
	connectToDevTools: true,

	name: 'apollo-client-dev',
	version: '1.3',
	queryDeduplication: false,
	defaultOptions: {
		watchQuery: {
			fetchPolicy: 'cache-and-network',
		},
	},
})
'use client'

import { Button } from '@/components/ui/button'
import { gql, useMutation, useQuery } from '@apollo/client'

const CREATE_POST = gql`
	mutation CreatePost {
		createPost(post: { userId: 1, title: "title", body: "body" }) {
			id
			title
			body
		}
	}
`

const GET_POSTS = gql`
	query GetPosts {
		posts {
			id
			title
			body
		}
	}
`

type Post = {
	id: number
	title: string
}

const Home = () => {
	const { loading, error, data } = useQuery(GET_POSTS)
	const [addPost, { data: mutationData }] = useMutation(CREATE_POST, {
		update(cache, { data: { addPost } }) {
			cache.modify({
				fields: {
					posts(existingPosts = []) {
						const newPostRef = cache.writeFragment({
							data: addPost,
							fragment: gql`
								fragment NewPost on Post {
									id
									text
									completed
								}
							`,
						})
						return [...existingPosts, newPostRef]
					},
				},
			})
		},
	})

	if (loading) return 'Loading...'
	if (error) return `Error! ${error.message}`

	return (
		<div>
			<Button
				onClick={() => {
					addPost()
					console.log(mutationData)
				}}
			>
				addPost
			</Button>
			{data.posts.map((post: Post) => (
				<p key={post.id}>
					{post.id}: {post.title}
				</p>
			))}
		</div>
	)
}

export default Home

@apollo/client version

^3.13.8

Apollo Client Devtools version

4.18.15 (Firefox)

drujbanjo avatar Jul 06 '25 15:07 drujbanjo

That should be working. Are you opening this in an iframe or anything like that?


Apart from that, one other thing: The way you are using Apollo Client here, you are sharing one long-running instance between all server side renders of your client components (yes, client components render on the server too) - you should never do that as it can lead to leaks of private data between users.

If you are using a SSR framework like Next.js, you need to take additional steps, in this case you need to use the @apollo/client-integration-nextjs package, you cannot use plain Apollo Client.

phryneas avatar Jul 07 '25 07:07 phryneas

Это должно работать. Вы открываете это в iframe или чем-то подобном?

Помимо этого, еще одно: при использовании Apollo Client вы совместно используете один долго выполняющийся экземпляр между всеми серверными рендерами ваших клиентских компонентов (да, клиентские компоненты также рендерятся на сервере) — этого делать ни в коем случае не следует, так как это может привести к утечке личных данных между пользователями.

Если вы используете фреймворк SSR, такой как Next.js, вам необходимо предпринять дополнительные шаги. В этом случае вам необходимо использовать пакет @apollo/client-integration-nextjs . Использовать простой клиент Apollo нельзя.

I don't use iframe. The site is rendered using next dev --turbopack. Before I installed @apollo/client-integration-nextjs, I had to restart the application every time I changed it because when I refreshed the page, Dev Tools didn't connect. Now that I have installed this library and configured it as described in the documentation, Dev Tools does not connect to the page at all.

The page is rendered as a client page.

Dev tools version - 4.19.13

{
  "name": "apollo",
  "version": "0.1.0",
  "private": true,
  "scripts": {
    "dev": "next dev --turbopack",
    "build": "next build",
    "start": "next start",
    "lint": "next lint"
  },
  "dependencies": {
    "@apollo/client": "^3.13.8",
    "@apollo/client-integration-nextjs": "^0.12.2",
    "@radix-ui/react-slot": "^1.2.3",
    "class-variance-authority": "^0.7.1",
    "clsx": "^2.1.1",
    "graphql": "^16.11.0",
    "lucide-react": "^0.525.0",
    "next": "15.3.4",
    "react": "^19.0.0",
    "react-dom": "^19.0.0",
    "tailwind-merge": "^3.3.1"
  },
  "devDependencies": {
    "@eslint/eslintrc": "^3",
    "@tailwindcss/postcss": "^4",
    "@types/node": "^20",
    "@types/react": "^19",
    "@types/react-dom": "^19",
    "eslint": ">=9.25.0",
    "eslint-config-next": "15.3.4",
    "eslint-config-xo": "^0.47.0",
    "tailwindcss": "^4",
    "tw-animate-css": "^1.3.5",
    "typescript": "^5"
  }
}

Updated:

When I use the server component and launch the application, Dev Tools shows that I am not connected, but after I refresh the page, it shows that I am connected but does not show any requests or cache.

const { loading, error, data } = await  getClient().query({ query: GET_POSTS })

drujbanjo avatar Jul 08 '25 11:07 drujbanjo

If you do this:

const { loading, error, data } = await  getClient().query({ query: GET_POSTS })

the request happens only on the server, so on another machine - the browser DevTools won't know about it, and technically there is just no way to debug it - that's a conceptual limitation of server components.

I don't use iframe. The site is rendered using next dev --turbopack. Before I installed @apollo/client-integration-nextjs, I had to restart the application every time I changed it because when I refreshed the page, Dev Tools didn't connect.

That doesn't sound right - restarting the application should never have any influence here. The DevTools are something that happens between your website in your browser and the devtools - restarting the browser shouldn't cause anything to happen.

Now that I have installed this library and configured it as described in the documentation, Dev Tools does not connect to the page at all.

Are you still using Client Components? The library has different patterns for server components and client components.


Generally, this is really hard to debug without seeing it - could you create a minimal version of your setup that doesn't connect and share that with us so we can take a look?

phryneas avatar Jul 08 '25 16:07 phryneas

If you do this:

const { loading, error, data } = await  getClient().query({ query: GET_POSTS })

the request happens only on the server, so on another machine - the browser DevTools won't know about it, and technically there is just no way to debug it - that's a conceptual limitation of server components.

I don't use iframe. The site is rendered using next dev --turbopack. Before I installed @apollo/client-integration-nextjs, I had to restart the application every time I changed it because when I refreshed the page, Dev Tools didn't connect.

That doesn't sound right - restarting the application should never have any influence here. The DevTools are something that happens between your website in your browser and the devtools - restarting the browser shouldn't cause anything to happen.

Now that I have installed this library and configured it as described in the documentation, Dev Tools does not connect to the page at all.

Are you still using Client Components? The library has different patterns for server components and client components.

Generally, this is really hard to debug without seeing it - could you create a minimal version of your setup that doesn't connect and share that with us so we can take a look?

I restart the Next.js application every time I refresh the page in the browser. I do NOT use iframe. I use a client page with a hook.

Here is the repository where the code I run is written and a video showing how I run it and what I do.

drujbanjo avatar Jul 10 '25 04:07 drujbanjo

Yeah, I can see this happening here.

Only in Firefox, only after a page refresh. Closing and reopening the DevTools makes it work again.

Thank you for reporting this! It will probably take a bit until we can get to fixing this as we're in the stretches of finalizing Apollo Client 4.0. In the meantime you should be able to get around that by closing and opening the Devtools by pressing F12 twice.

phryneas avatar Jul 10 '25 08:07 phryneas

Yeah, I can see this happening here.

Only in Firefox, only after a page refresh. Closing and reopening the DevTools makes it work again.

Thank you for reporting this! It will probably take a bit until we can get to fixing this as we're in the stretches of finalizing Apollo Client 4.0. In the meantime you should be able to get around that by closing and opening the Devtools by pressing F12 twice.

And it's true. When I close and reopen dev tools, everything works fine. Thank you for your reply ❤️.

drujbanjo avatar Jul 10 '25 10:07 drujbanjo

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.

github-actions[bot] avatar Jul 10 '25 10:07 github-actions[bot]

Let's keep this open so we can track the bug until we get to fix it :)

phryneas avatar Jul 10 '25 10:07 phryneas

I'm getting this for Firefox only as well (Chrome works fine). I've noticed that if I set a breakpoint right before the ApolloClient is initialized in the code then manually resume execution, the extension in Firefox works without issue without having to open and close the browser devtools. This is using a non-Next React app, Client v3.13.8, devtools v4.21.9, Firefox 144.0.

karmeleon avatar Oct 27 '25 22:10 karmeleon