Mercurius Auth is a Fastify plugin designed to add configurable authentication and authorization support to GraphQL APIs built with Mercurius. It is currently at stable version 6.0.0, with major updates often aligning with new Fastify or Mercurius versions. The plugin allows defining auth directives directly within the GraphQL schema to apply custom policies against protected fields, supporting both normal and gateway modes. Alternatively, it can operate in an 'External Policy' mode, offering programmatic control over authorization. Key differentiators include its tight integration with the Fastify and Mercurius ecosystems, its ability to build an auth context, and its GraphQL spec compliance, including features like schema filtering and replacement. Development appears active, with regular updates and dependency bumps.
npm install mercurius-authVerified import paths — ran on the pinned version, not inferred.
This quickstart demonstrates `mercurius-auth` in 'Directive mode' using Fastify and Mercurius. It defines a custom `@auth` directive with role-based authorization, extracting the user role from request headers in `authContext` and enforcing policies in `applyPolicy`.
Ensure your project is using Fastify v4 or greater, and ideally Fastify v5 compatible versions when using mercurius-auth v6.0.0. Update your `fastify` and `mercurius` packages accordingly.
Upgrade your Fastify dependency to v4 or newer. Review your Fastify application code for any breaking changes introduced in Fastify v4 and update accordingly. Ensure Mercurius is also compatible with Fastify v4.
No direct code changes are typically required unless you were directly interacting with or extending internal components that relied on `@graphql-tools/wrap` within mercurius-auth. Ensure thorough testing after upgrading.
Adopt ESM `import` statements consistently across your Fastify and Mercurius application, especially if your `package.json` specifies `"type": "module"`.
Always register `mercurius-auth` using `app.register(mercuriusAuth, options)` where `app` is your Fastify instance.
Ensure your Fastify and Mercurius versions are compatible with `mercurius-auth`. Specifically, `mercurius-auth` v3+ requires Fastify v4+. Also, check your Mercurius registration for proper context propagation.
Make sure your GraphQL schema includes the directive definition (e.g., `directive @auth(...)`) and that the `authDirective` option in `app.register(mercuriusAuth, { authDirective: 'auth' })` matches your directive name.