Drivly's Auth.js library for Itty Router
npm install @drivly/itty-authjsThis package has a peer dependency on itty-router, so you'll need to install it as well:
npm install itty-routerBefore 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 endpointsimport{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,}),],}}exportdefaultrouterimport{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())exportdefaultrouterIf 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())exportdefaultrouterThe 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.
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.
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,},})AuthRequest: Extended Itty-Router request with auth propertiesAuthEnv: Environment type with Auth.js requirementsAuthUser: User data from authenticationAuthConfig: Auth.js configuration typeConfigHandler: Function type for auth configuration callbacks
The IAuth namespace also includes these types:
IAuth.Request: Same asAuthRequestIAuth.Env: Same asAuthEnvIAuth.User: Same asAuthUserIAuth.Config: Same asAuthConfigIAuth.Handler: Same asConfigHandler
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'}}}