Skip to content

Repository files navigation

Auth.js middleware for Itty-Router

Drivly's Auth.js library for Itty Router

Installation

npm install @drivly/itty-authjs

This package has a peer dependency on itty-router, so you'll need to install it as well:

npm install itty-router

Configuration

Before using the middleware, you need to configure the environment variables for the authentication.

AUTH_SECRET=#required - a random string used to encrypt cookies and tokens
AUTH_URL=#optional - custom URL for auth endpoints

Usage

Basic Setup

import{IAuth,typeAuthRequest,typeAuthEnv}from'@drivly/itty-authjs'importGitHubfrom'@auth/core/providers/github'import{AutoRouter}from'itty-router'constrouter=AutoRouter<AuthRequest,[AuthEnv]>()// Add auth configuration middleware to all routesrouter.all('*',IAuth.setup(getAuthConfig))// Handle Auth.js routesrouter.all('/api/auth/*',IAuth.handler())// Add authentication middleware to protected routesrouter.all('/api/*',IAuth.require())// Access auth user data in protected routesrouter.get('/api/protected',(request)=>{constauth=request.authUserreturnauth})// Auth configuration functionfunctiongetAuthConfig(request: AuthRequest,env: AuthEnv){return{secret: env.AUTH_SECRET,providers: [GitHub({clientId: env.GITHUB_ID,clientSecret: env.GITHUB_SECRET,}),],}}exportdefaultrouter

Simplified Setup Using createConfig

import{IAuth,typeAuthRequest,typeAuthEnv}from'@drivly/itty-authjs'importGitHubfrom'@auth/core/providers/github'import{AutoRouter}from'itty-router'constrouter=AutoRouter<AuthRequest,[AuthEnv]>()// Create a config with GitHub providerconstauthConfig=IAuth.createConfig({providers: [GitHub({clientId: 'GITHUB_ID',clientSecret: 'GITHUB_SECRET',}),],// Optional: customize base path (defaults to /api/auth)basePath: '/auth',// Optional: additional Auth.js optionsadditionalOptions: {pages: {signIn: '/login',},},})// Use the created configrouter.all('*',IAuth.setup(authConfig))router.all('/auth/*',IAuth.handler())router.all('/api/*',IAuth.require())exportdefaultrouter

Using Direct Function Imports

If you prefer direct function imports instead of the namespace approach:

import{setupAuth,requireAuth,handleAuthRoutes,createConfig,typeAuthRequest,typeAuthEnv,}from'@drivly/itty-authjs'importGitHubfrom'@auth/core/providers/github'import{AutoRouter}from'itty-router'constrouter=AutoRouter<AuthRequest,[AuthEnv]>()// Create a config with GitHub providerconstauthConfig=createConfig({providers: [GitHub({clientId: 'GITHUB_ID',clientSecret: 'GITHUB_SECRET',}),],})router.all('*',setupAuth(authConfig))router.all('/api/auth/*',handleAuthRoutes())router.all('/api/*',requireAuth())exportdefaultrouter

API Reference

IAuth Namespace

The IAuth namespace provides a cleaner way to import and use the library:

  • IAuth.setup(configFn): Sets up Auth.js configuration for the environment.
  • IAuth.handler(): Handles Auth.js routes.
  • IAuth.require(): Middleware that requires authentication.
  • IAuth.createConfig(options): Utility to easily create a config handler function with sensible defaults.

Methods

  • setupAuth(configFn): Sets up Auth.js configuration for the environment.
  • handleAuthRoutes(): Handles Auth.js routes.
  • requireAuth(): Middleware that requires authentication.
  • createConfig(options): Utility to easily create a config handler function with sensible defaults.

createConfig Options

The createConfig function accepts the following options:

interfaceCreateConfigOptions{providers: Array<Provider>// Auth.js providersbasePath?: string// Optional custom base path (defaults to /api/auth)additionalOptions?: Partial<Omit<AuthConfig,'providers'|'basePath'>>// Any other Auth.js options}

Example usage:

constauthConfig=createConfig({providers: [GitHub({clientId: 'GITHUB_ID',clientSecret: 'GITHUB_SECRET',}),],basePath: '/auth',additionalOptions: {pages: {signIn: '/custom-login',},trustHost: true,},})

Types

  • AuthRequest: Extended Itty-Router request with auth properties
  • AuthEnv: Environment type with Auth.js requirements
  • AuthUser: User data from authentication
  • AuthConfig: Auth.js configuration type
  • ConfigHandler: Function type for auth configuration callbacks

IAuth Namespace Types

The IAuth namespace also includes these types:

  • IAuth.Request: Same as AuthRequest
  • IAuth.Env: Same as AuthEnv
  • IAuth.User: Same as AuthUser
  • IAuth.Config: Same as AuthConfig
  • IAuth.Handler: Same as ConfigHandler

Advanced Configuration

For more advanced Auth.js configuration options, refer to the Auth.js documentation.

functiongetAuthConfig(request: AuthRequest,env: AuthEnv){return{secret: env.AUTH_SECRET,providers: [...],callbacks: {asyncsession({ session, token, user }){// Custom session handlingreturnsession},asyncjwt({ token, user, account, profile }){// Custom JWT handlingreturntoken}},// Other Auth.js optionspages: {signIn: '/custom-signin'}}}

About

Drivly's Auth.js library for Itty Router

Resources

Stars

0 stars

Watchers

1 watching

Forks

Releases

Packages

Used by

Contributors

Languages