{"id":17667,"library":"grant-koa","title":"Grant Koa OAuth Proxy Middleware","description":"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.","status":"active","version":"5.4.8","language":"javascript","source_language":"en","source_url":"https://github.com/simov/grant","tags":["javascript","oauth","oauth2","openid","openid-connect","authentication","authorization","proxy","middleware","typescript"],"install":[{"cmd":"npm install grant-koa","lang":"bash","label":"npm"},{"cmd":"yarn add grant-koa","lang":"bash","label":"yarn"},{"cmd":"pnpm add grant-koa","lang":"bash","label":"pnpm"}],"dependencies":[{"reason":"Required peer dependency as it's a Koa middleware.","package":"koa","optional":false}],"imports":[{"note":"While CommonJS `require` still works for basic usage, modern Koa applications increasingly favor ESM. The primary export is a function that returns the middleware.","wrong":"const grant = require('grant-koa');","symbol":"grant","correct":"import grant from 'grant-koa';\n// or\nimport Grant from 'grant-koa';"},{"note":"Imports for TypeScript types like `GrantMiddleware` provide type safety and improved developer experience when configuring or using the middleware. The package ships TypeScript types.","symbol":"GrantMiddleware","correct":"import Grant, { GrantMiddleware } from 'grant-koa';\n// Used for type hinting in TypeScript"},{"note":"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`.","symbol":"Koa context typing","correct":"import { Context } from 'koa';\n\ninterface CustomContext extends Context {\n  session: Record<string, any>;\n  // ... potentially other grant-specific properties\n}"}],"quickstart":{"code":"import Koa from 'koa';\nimport Router from '@koa/router';\nimport session from 'koa-session';\nimport Grant from 'grant-koa';\n\nconst app = new Koa();\nconst router = new Router();\n\n// Koa session is required by grant-koa\napp.keys = ['your-secret-session-key']; // Replace with a strong secret\napp.use(session({}, app));\n\nconst grantConfig = {\n  defaults: {\n    origin: 'http://localhost:3000',\n    transport: 'session',\n    state: true,\n  },\n  google: {\n    key: process.env.GOOGLE_CLIENT_ID ?? 'YOUR_GOOGLE_CLIENT_ID',\n    secret: process.env.GOOGLE_CLIENT_SECRET ?? 'YOUR_GOOGLE_CLIENT_SECRET',\n    scope: ['openid', 'profile', 'email'],\n    callback: '/connect/google/callback',\n  },\n};\n\n// Initialize Grant middleware\nconst grant = Grant(grantConfig);\napp.use(grant as Koa.Middleware); // Type assertion might be needed depending on Koa version/types\n\n// OAuth initiation route\nrouter.get('/connect/google', async (ctx) => {\n  ctx.redirect('/connect/google'); // Redirects to grant-koa for OAuth flow\n});\n\n// OAuth callback route\nrouter.get('/connect/google/callback', async (ctx) => {\n  if (ctx.session?.grant?.response?.access_token) {\n    ctx.body = `Hello, your Google access token is: ${ctx.session.grant.response.access_token}`;\n  } else {\n    ctx.body = 'Authentication failed or cancelled.';\n  }\n});\n\napp.use(router.routes()).use(router.allowedMethods());\n\napp.listen(3000, () => {\n  console.log('Koa app listening on http://localhost:3000');\n  console.log('Initiate Google OAuth by visiting http://localhost:3000/connect/google');\n});","lang":"typescript","description":"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."},"warnings":[{"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.","message":"Koa 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.","severity":"breaking","affected_versions":"koa>=3.0.0"},{"fix":"Always ensure `koa-session` (or an equivalent) is installed and used as `app.use(session({}, app));` prior to `app.use(grant);`.","message":"`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.","severity":"gotcha","affected_versions":">=1.0.0"},{"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.","message":"Incorrect `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.","severity":"gotcha","affected_versions":">=1.0.0"},{"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.","message":"Older 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.","severity":"deprecated","affected_versions":"<5.0.0"}],"env_vars":null,"last_verified":"2026-04-23T00:00:00.000Z","next_check":"2026-07-22T00:00:00.000Z","problems":[{"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);`.","cause":"The `grant` instance was not called as a function, or `koa-session` was not initialized correctly before `grant-koa`.","error":"TypeError: app.use() expects a middleware function"},{"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.","cause":"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).","error":"OAuth error: redirect_uri_mismatch"},{"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.","cause":"The `key` (client ID) or `secret` (client secret) for an OAuth provider in the `grantConfig` is missing or incorrect.","error":"Error: Grant: missing or invalid credentials for [provider]"}],"ecosystem":"npm","meta_description":null,"install_score":null,"install_tag":null,"quickstart_score":null,"quickstart_tag":null}