Registry / web-framework / mercurius-auth

mercurius-auth

JSON →
library6.0.0jsnpmunverified

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-auth
INSTALL
IMPORT
SIG · MERCURIUS-AUTH
M
mercurius-auth
web-frameworkjavascriptv6.0.0
Install
Import
Disk
Pass rate
0/ 6
Env Coverage0 / 6
glibc
1822
musl
1822
Install & Compatibility
Where this runs
tested against v? · npm install
Install × environment matrix
Each cell = how many times install + import succeeded across repeated harness runs. Partial = flaky.
glibc = Debian/Ubuntu slim · musl = Alpine Linux
musl
node 18226 runs
build_error
glibc
node 18226 runs
build_error
Code
Verified usage

Verified import paths — ran on the pinned version, not inferred.

mercuriusAuth
import mercuriusAuth from 'mercurius-auth'
const mercuriusAuth = require('mercurius-auth')
While CommonJS `require` works for older Node.js versions or specific configurations, modern Fastify/Mercurius setups often prefer ESM `import`.
Fastify
import Fastify from 'fastify'
const Fastify = require('fastify')
Fastify itself supports both CJS and ESM; consistency with your project's module system is recommended.
mercurius
import mercurius from 'mercurius'
const mercurius = require('mercurius')
Mercurius, like Fastify, supports both CJS and ESM. Use `import` for modern setups.

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`.

import Fastify from 'fastify'; import mercurius from 'mercurius'; import mercuriusAuth from 'mercurius-auth'; const app = Fastify(); const schema = ` directive @auth( requires: Role = ADMIN, ) on OBJECT | FIELD_DEFINITION enum Role { ADMIN REVIEWER USER UNKNOWN } type Query { add(x: Int, y: Int): Int @auth(requires: USER) adminData: String @auth(requires: ADMIN) } `; const resolvers = { Query: { add: async (_, { x, y }) => x + y, adminData: async () => 'Secret admin information' } }; app.register(mercurius, { schema, resolvers }); app.register(mercuriusAuth, { authContext (context) { // Simulate loading user identity from request headers const identity = context.reply.request.headers['x-user'] || 'UNKNOWN'; return { identity: identity.toUpperCase() // Ensure consistency }; }, async applyPolicy (authDirectiveAST, parent, args, context, info) { const requiredRole = authDirectiveAST.requires; const userRole = context.auth.identity; // Assuming identity is the role for simplicity if (requiredRole === 'ADMIN' && userRole !== 'ADMIN') { return false; } if (requiredRole === 'USER' && (userRole !== 'ADMIN' && userRole !== 'USER')) { return false; } return true; // Policy passes }, authDirective: 'auth' }); app.listen({ port: 3000 }, (err) => { if (err) { app.log.error(err); process.exit(1); } app.log.info(`Server listening on port 3000`); }); // Example usage (e.g., with curl): // curl -H "x-user: user" http://localhost:3000/graphql -X POST -H "Content-Type: application/json" -d '{"query":"query { add(x: 5, y: 3) }"}' // curl -H "x-user: admin" http://localhost:3000/graphql -X POST -H "Content-Type: application/json" -d '{"query":"query { adminData }"}' // curl -H "x-user: user" http://localhost:3000/graphql -X POST -H "Content-Type: application/json" -d '{"query":"query { adminData }"}' // Should fail
Debug
Known issues
breakingVersion 6.0.0 of mercurius-auth introduces compatibility changes to prepare for Fastify v5. While it might still work with Fastify v4, it is highly recommended to upgrade Fastify to its latest major version alongside mercurius-auth v6.0.0 to ensure full compatibility and avoid potential issues. This aligns with Fastify's plugin API evolution.
fix
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.
affects: >=6.0.0
breakingVersion 3.0.0 of mercurius-auth upgraded its core dependency to Fastify v4. This is a significant breaking change as Fastify v4 introduced several API changes, particularly around plugin registration and decorators. Directly incompatible Fastify v3 usage will result in runtime errors.
fix
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.
affects: >=3.0.0 <6.0.0
breakingMercurius Auth v2.0.2 removed the `@graphql-tools/wrap` dependency and replaced its functionality internally. While this primarily impacted internal implementation, it might have subtle effects if your application relied on specific behaviors or types exposed by that dependency through earlier mercurius-auth versions.
fix
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.
affects: >=2.0.2
gotchaWhen using `mercurius-auth` in ESM modules, ensure you use `import mercuriusAuth from 'mercurius-auth'` instead of `require`. While Fastify and Mercurius generally handle both, mixing module systems can lead to unexpected errors or require specific build configurations.
fix
Adopt ESM `import` statements consistently across your Fastify and Mercurius application, especially if your `package.json` specifies `"type": "module"`.
affects: >=1.0.0
Errors
Common errors & fixes
Error: mercuriusAuth must be used as a Fastify plugin, i.e. `fastify.register(mercuriusAuth)`
Attempting to initialize `mercurius-auth` directly without using `fastify.register()` or passing incorrect options to `register`.
fix
Always register `mercurius-auth` using `app.register(mercuriusAuth, options)` where `app` is your Fastify instance.
TypeError: Cannot read properties of undefined (reading 'request') in authContext
This error often occurs when `context.reply.request` is `undefined` within `authContext`, usually due to an incompatible Fastify version or a misconfigured Mercurius instance not properly passing the Fastify context.
fix
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.
Error: Unknown directive "@auth".
The `@auth` directive (or your custom directive name) has been used in the schema but was not properly defined in the `mercurius-auth` options or included in the `authDirective` option.
fix
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.
Upgrade
Version history
6.0.0latest on npm
Audit
Dependencies
fastifyrequiredmercurius-auth is a Fastify plugin and registers with a Fastify instance.
mercuriusrequiredmercurius-auth extends Mercurius to provide GraphQL authentication and authorization.
Agent activity
5 hits · last 30 days
node
4
OpenAI (training)
1
Resources