A serverless authentication service built with BetterAuth, Express.js, and AWS Lambda. This service provides scalable authentication with a custom Lambda authorizer for API Gateway.
- AWS Lambda - Serverless compute
- Express.js - Web framework
- BetterAuth - Authentication library
- Prisma - PostgreSQL ORM
- Serverless Framework v4 - Deployment
- Node.js 22 - Runtime
- Node.js 22+
- Yarn 4+ (
corepack enable) - PostgreSQL database
- AWS account (for deployment)
-
Install dependencies
yarn install
-
Environment configuration Create
.envfile:# Database DATABASE_URL="postgresql://username:password@localhost:5432/auth_service" # BetterAuth BETTER_AUTH_SECRET="your-secret-key" BASE_URL="http://localhost:3000" REDIRECT_DOMAIN="http://localhost:3000" # CORS ALLOWED_ORIGINS="http://localhost:3000" # AWS (for deployment) AWS_REGION="us-west-1" AWS_ACCESS_KEY_ID="your-key" AWS_SECRET_ACCESS_KEY="your-secret"
-
Database setup
yarn prisma generate yarn migrate:dev
-
Start development server
yarn start
The service will be available at http://localhost:3000/auth/
API Gateway → Lambda Authorizer → Lambda Function → Express.js → BetterAuth → PostgreSQL
The service includes a custom Lambda authorizer (src/functions/auth/authorizer/handler.ts) that validates JWT tokens from BetterAuth for API Gateway requests.
yarn startyarn deploy
yarn deploy --stage prodEdit src/lib/auth.ts to configure authentication options. For detailed BetterAuth configuration options, see the official documentation.
| Variable | Description | Required |
|---|---|---|
DATABASE_URL |
PostgreSQL connection string | ✅ |
BETTER_AUTH_SECRET |
JWT signing secret | ✅ |
BASE_URL |
Application base URL | ✅ |
REDIRECT_DOMAIN |
OAuth redirect domain | ✅ |
ALLOWED_ORIGINS |
CORS origins | ✅ |
BetterAuth automatically generates authentication endpoints:
POST /auth/signin- Sign inPOST /auth/signup- Sign upPOST /auth/signout- Sign outGET /auth/session- Get sessionPOST /auth/verify-email- Verify emailGET /auth/oauth/{provider}- OAuth flowPOST /auth/forgot-password- Password resetPOST /auth/2fa/enable- Enable 2FA
Add new Lambda functions in src/functions/ and register them in serverless.ts.
This service can be extended according to the BetterAuth documentation. Add custom plugins, hooks, and configurations in src/lib/auth.ts.
Add custom models to prisma/schema.prisma and run yarn migrate:dev.
yarn test
yarn test:watchyarn start- Start development serveryarn deploy- Deploy to AWSyarn test- Run testsyarn migrate:dev- Run database migrationsyarn lint- Lint codeyarn format- Format code
ISC License