This is a backend-only API project built with Next.js (App Router), Auth.js v5.0.0, and SurrealDB. It provides JWT-based authentication for protected API routes.
- Next.js App Router with TypeScript
- Auth.js v5.0.0 integration
- SurrealDB database integration
- JWT-based authentication
- Protected API routes
- Middleware for route protection
- Node.js 18.x or later
- SurrealDB installed and running
git clone <repository-url>
cd <repository-directory>
npm install
Copy the .env.example
file to .env
and update the values:
cp .env.example .env
Update the following variables in the .env
file:
# Auth.js Configuration
AUTH_SECRET=your-auth-secret-key-here
AUTH_URL=http://localhost:3000
# SurrealDB Configuration
SURREALDB_URL=http://localhost:8000
SURREALDB_NAMESPACE=test
SURREALDB_DATABASE=test
SURREALDB_USERNAME=root
SURREALDB_PASSWORD=root
# JWT Configuration
JWT_SECRET=your-jwt-secret-key-here
JWT_EXPIRATION=86400 # 24 hours in seconds
Start SurrealDB with the following command:
surreal start --log debug --user root --pass root memory
npm run dev
The API will be available at http://localhost:3000.
- POST /api/auth/token
- Request body:
{ "email": "user@example.com", "password": "password123" }
- Response:
{ "token": "jwt-token-here" }
- Request body:
- GET /api/protected/data
- Headers:
Authorization: Bearer <jwt-token>
- Response: Protected data
- Headers:
- GET /api/health
- Response:
{ "status": "ok", "timestamp": "2023-06-01T12:00:00.000Z", "version": "1.0.0" }
- Response:
To add a user to the database, you can use the SurrealDB CLI or any SurrealDB client. Here's an example using the SurrealDB CLI:
CREATE user:user1 CONTENT {
email: "user@example.com",
password: crypto::argon2::generate("password123"),
name: "Test User",
role: "user"
};
- Client sends credentials to
/api/auth/token
- Server validates credentials against SurrealDB
- If valid, server generates a JWT and returns it
- Client includes the JWT in the
Authorization
header for protected routes - Middleware validates the JWT for all routes under
/api/protected/*
MIT