Creating Apollo Client in Next Middleware breaks next build
Unanswered
Bigheaded ant posted this in #help-forum
Bigheaded antOP
I have a Next application, and I've added middleware logic in middleware.ts to fetch some user data using apollo, and on occasion redirect the user based off the data returned in the request. Everything works locally in a dev environment; however, running "next build" fails because of the apollo client being created.
The specific error returned when running the build is this:
Code example in middleware.ts:
Does anyone know how to fix this build and still use the apollo client in the Next middle ware? Any help/advice is greatly appreciated.
The specific error returned when running the build is this:
> next build
â–² Next.js 14.0.4
- Environments: .env.local, .env.production
Failed to compile.
./node_modules/apollo-utilities/node_modules/ts-invariant/lib/invariant.esm.js
Dynamic Code Evaluation (e. g. 'eval', 'new Function', 'WebAssembly.compile') not allowed in Edge Runtime
Learn More: https://nextjs.org/docs/messages/edge-dynamic-code-evaluationCode example in middleware.ts:
if (authenticated) {
try {
const client = await getServerSideApolloClient();
const response = await client.query({
query: QUERY,
fetchPolicy: 'network-only',
});
const data = response.data;
if (data.something) {
return NextResponse.redirect(new URL('/some-page', request.url));
} else if (data.otherThing) {
return NextResponse.redirect(new URL('/some-other-page', request.url));
}
return NextResponse.next();
} catch (e) {
return NextResponse.next();
}Does anyone know how to fix this build and still use the apollo client in the Next middle ware? Any help/advice is greatly appreciated.
5 Replies
Masai Lion
The error you encounter is due to next js middleware.js/ts has a edge runtime and not node js runtime. You can not use node js runtimes inside the middleware. As a work around you either need to create an api route that your middleware can call fetch to it or use the Apollo package specific edge runtime functionality if that even exist.
Bigheaded antOP
Thank you for the response. I don't think that exists on Apollo's end.
I ended up going with this in the middleware:
const response = await fetch(uri, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
Authorization: session.tokens.idToken.toString(),
},
body: JSON.stringify({
query: gqlQueryString,
}),
cache: 'no-cache',
});It works, but it's annoying that it forces my requests to be inconsistent. Setting up Api routes that do the calls for me is a really good idea
Masai Lion
Happy to help 🙂 have a nice day!