Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Apollo Server Express: Request entity too large

I need to POST a large payload in a GraphQL mutation. How do I increase the body size limit of Apollo Server?

I'm using apollo-server-express version 2.9.3.

My code (simplified):

const myGraphQLSchema = new GraphQLSchema({
  query: new GraphQLObjectType({
    name: 'Query',
    fields: {
      user: UserQuery,
    },
  }),
  mutation: new GraphQLObjectType({
    name: 'Mutation',
    fields: () => ({
      ...UserMutations,
    }),
  }),
});

const apolloServer = new ApolloServer(schema: myGraphQLSchema);

const app = express();
app.use(apolloServer.getMiddleware({ path: '/graphql' });
like image 298
Martin Konicek Avatar asked Aug 30 '26 20:08

Martin Konicek


2 Answers

Not exactly sure in which version it was added, but on 2.9.15 you can apply it in applyMiddleware function.

const apolloServer = new ApolloServer(someConfig);
apolloServer.applyMiddleware({
  app,
  cors: {
    origin: true,
    credentials: true,
  },
  bodyParserConfig: {
    limit:"10mb"
  }
});
like image 92
Maxrain Avatar answered Sep 02 '26 19:09

Maxrain


Simply add an Express body parser before your Apollo server middleware:

import { json } from 'express';

app.use(json({ limit: '2mb' }));
app.use(apolloServer.getMiddleware({ path: '/graphql' });

If you want to get fancy, you can have a separate body size limit for authenticated vs unauthenticated requests:

const jsonParsers = [
  json({ limit: '16kb' }),
  json({ limit: '2mb' }),
];

function parseJsonSmart(req: Request, res: Response, next: NextFunction) {
  // How exactly you do auth depends on your app
  const isAuthenticated = req.context.isAuthenticated();
  return jsonParsers[isAuthenticated ? 1 : 0](req, res, next);
}

app.use(parseJsonSmart);
app.use(apolloServer.getMiddleware({ path: '/graphql' });
like image 22
Martin Konicek Avatar answered Sep 02 '26 20:09

Martin Konicek



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!