Registry / auth-security / grant-koa

grant-koa

JSON →
library5.4.8jsnpmunverified

grant-koa is a specialized middleware designed to integrate the Grant OAuth Proxy into Koa.js applications. It abstracts the complexities of OAuth and OpenID Connect flows, providing a unified interface for authenticating users against various identity providers (e.g., Google, GitHub, Facebook). The current stable version is 5.4.8. As an adapter for the core `grant` library, its release cadence is generally tied to updates in `grant` and compatibility with major Koa versions. This package is crucial for Koa developers needing to implement robust and flexible authentication/authorization without deep diving into each OAuth provider's specific API, offering a streamlined approach to secure user access and data.

npm install grant-koa
INSTALL
IMPORT
SIG · GRANT-KOA
G
grant-koa
auth-securityjavascriptv5.4.8
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.

grant
import grant from 'grant-koa'; // or import Grant from 'grant-koa';
const grant = require('grant-koa');
While CommonJS `require` still works for basic usage, modern Koa applications increasingly favor ESM. The primary export is a function that returns the middleware.
GrantMiddleware
import Grant, { GrantMiddleware } from 'grant-koa'; // Used for type hinting in TypeScript
Imports for TypeScript types like `GrantMiddleware` provide type safety and improved developer experience when configuring or using the middleware. The package ships TypeScript types.
Koa context typing
import { Context } from 'koa'; interface CustomContext extends Context { session: Record<string, any>; // ... potentially other grant-specific properties }
While `grant-koa` provides its types, integrating with Koa's `Context` requires explicit type extension in TypeScript for properties like `session` which are essential for `grant-koa`'s operation, usually provided by `koa-session`.

This quickstart demonstrates setting up `grant-koa` with a basic Koa application, integrating `koa-session` (a prerequisite) and a simple Google OAuth flow using placeholder credentials. It shows how to initiate the OAuth process and handle the callback, accessing the authenticated user's token from the session.

import Koa from 'koa'; import Router from '@koa/router'; import session from 'koa-session'; import Grant from 'grant-koa'; const app = new Koa(); const router = new Router(); // Koa session is required by grant-koa app.keys = ['your-secret-session-key']; // Replace with a strong secret app.use(session({}, app)); const grantConfig = { defaults: { origin: 'http://localhost:3000', transport: 'session', state: true, }, google: { key: process.env.GOOGLE_CLIENT_ID ?? 'YOUR_GOOGLE_CLIENT_ID', secret: process.env.GOOGLE_CLIENT_SECRET ?? 'YOUR_GOOGLE_CLIENT_SECRET', scope: ['openid', 'profile', 'email'], callback: '/connect/google/callback', }, }; // Initialize Grant middleware const grant = Grant(grantConfig); app.use(grant as Koa.Middleware); // Type assertion might be needed depending on Koa version/types // OAuth initiation route router.get('/connect/google', async (ctx) => { ctx.redirect('/connect/google'); // Redirects to grant-koa for OAuth flow }); // OAuth callback route router.get('/connect/google/callback', async (ctx) => { if (ctx.session?.grant?.response?.access_token) { ctx.body = `Hello, your Google access token is: ${ctx.session.grant.response.access_token}`; } else { ctx.body = 'Authentication failed or cancelled.'; } }); app.use(router.routes()).use(router.allowedMethods()); app.listen(3000, () => { console.log('Koa app listening on http://localhost:3000'); console.log('Initiate Google OAuth by visiting http://localhost:3000/connect/google'); });
Debug
Known issues
breakingKoa v3 removed support for generator functions, requiring all middleware to be `async/await`. Ensure your application and any other middleware are compatible with Koa v2+ (which `grant-koa` is designed for) and avoid generator-based middleware if upgrading Koa.
fix
Migrate any custom generator-based Koa middleware to async/await functions. `grant-koa` itself uses async/await internally, but userland middleware might need updates.
affects: koa>=3.0.0
gotcha`grant-koa` relies heavily on Koa's session middleware (`koa-session` or similar) to store transient OAuth state and tokens. Forgetting to configure or properly `app.use()` a session middleware *before* `grant-koa` will lead to authentication failures and errors.
fix
Always ensure `koa-session` (or an equivalent) is installed and used as `app.use(session({}, app));` prior to `app.use(grant);`.
affects: >=1.0.0
gotchaIncorrect `origin` or `callback` URLs in the `grantConfig` can cause 'redirect_uri_mismatch' errors with OAuth providers. These must exactly match the URLs registered with the OAuth provider.
fix
Double-check that `grantConfig.defaults.origin` and the `callback` URL specified for each provider (e.g., `google.callback`) precisely match the configured redirect URIs in your OAuth provider's developer console. Ensure 'http' vs 'https' and trailing slashes match.
affects: >=1.0.0
deprecatedOlder versions of `grant` (and thus `grant-koa` implicitly) might use less secure defaults or older OAuth specifications. Always refer to the latest `grant` documentation for security best practices, especially regarding `state` and `pkce` parameters.
fix
Upgrade to the latest stable version of `grant` and `grant-koa`. Review the `grant` configuration options for `state: true` and `pkce: true` (if supported by the provider) to enhance security against CSRF and authorization code interception attacks.
affects: <5.0.0
Errors
Common errors & fixes
TypeError: app.use() expects a middleware function
The `grant` instance was not called as a function, or `koa-session` was not initialized correctly before `grant-koa`.
fix
Ensure `const grant = Grant(grantConfig);` is correctly assigning the middleware function, and that `app.use(session({}, app));` is present and correctly configured before `app.use(grant);`.
OAuth error: redirect_uri_mismatch
The configured `callback` URL in `grantConfig` does not precisely match the redirect URI registered in the OAuth provider's application settings (e.g., Google Console).
fix
Verify that the `origin` and `callback` properties in your `grantConfig` exactly match the redirect URI registered with your OAuth provider, including protocol (http/https), hostname, port, and path.
Error: Grant: missing or invalid credentials for [provider]
The `key` (client ID) or `secret` (client secret) for an OAuth provider in the `grantConfig` is missing or incorrect.
fix
Ensure `process.env.YOUR_PROVIDER_CLIENT_ID` and `process.env.YOUR_PROVIDER_CLIENT_SECRET` are correctly set in your environment variables and that `grantConfig` is referencing them or providing valid hardcoded values.
Upgrade
Version history
5.4.8latest on npm
Audit
Dependencies
koarequiredRequired peer dependency as it's a Koa middleware.
Agent activity
13 hits · last 30 days
node
12
OpenAI (training)
1
Resources