{"id":29571950,"url":"https://github.com/G4brym/authentication-using-d1-example","last_synced_at":"2025-07-19T04:36:43.583Z","repository":{"id":170410549,"uuid":"646546572","full_name":"G4brym/authentication-using-d1-example","owner":"G4brym","description":"Implementing Register and Login in Cloudflare Workers using D1","archived":false,"fork":false,"pushed_at":"2025-06-14T21:52:26.000Z","size":503,"stargazers_count":59,"open_issues_count":0,"forks_count":7,"subscribers_count":2,"default_branch":"main","last_synced_at":"2025-06-25T07:05:57.965Z","etag":null,"topics":["cloudflare-workers","cloudflare-workers-d1","d1","example","example-project","workers","workers-d1"],"latest_commit_sha":null,"homepage":"https://massadas.com/posts/implementing-register-and-login-in-workers-d1/","language":"TypeScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/G4brym.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null,"zenodo":null}},"created_at":"2023-05-28T18:35:39.000Z","updated_at":"2025-06-19T10:18:18.000Z","dependencies_parsed_at":null,"dependency_job_id":"2f81b7fc-fce0-497a-8b7a-b1c0473b3d83","html_url":"https://github.com/G4brym/authentication-using-d1-example","commit_stats":null,"previous_names":["g4brym/authentication-using-d1-example"],"tags_count":0,"template":false,"template_full_name":null,"purl":"pkg:github/G4brym/authentication-using-d1-example","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/G4brym%2Fauthentication-using-d1-example","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/G4brym%2Fauthentication-using-d1-example/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/G4brym%2Fauthentication-using-d1-example/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/G4brym%2Fauthentication-using-d1-example/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/G4brym","download_url":"https://codeload.github.com/G4brym/authentication-using-d1-example/tar.gz/refs/heads/main","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/G4brym%2Fauthentication-using-d1-example/sbom","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":265889162,"owners_count":23844539,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["cloudflare-workers","cloudflare-workers-d1","d1","example","example-project","workers","workers-d1"],"created_at":"2025-07-19T04:36:42.422Z","updated_at":"2025-07-19T04:36:43.549Z","avatar_url":"https://github.com/G4brym.png","language":"TypeScript","readme":"# Example code for implementing Register and Login in Cloudflare Workers using D1\n\nThis project provides a practical example of implementing user registration and login functionality within a Cloudflare Workers environment, utilizing D1 for database storage. It demonstrates common authentication patterns, including password hashing and session token management, and serves as a companion to the [accompanying article](https://massadas.com/posts/implementing-register-and-login-in-workers-d1/).\n\nTechnologies used:\n- [hono](https://github.com/honojs/hono): A small, simple, and ultrafast web framework for the Edge, used here for routing.\n- [chanfana](https://github.com/cloudflare/chanfana): Employed for OpenAPI specification generation and request/response validation, ensuring API integrity.\n- [workers-qb](https://github.com/G4brym/workers-qb): A query builder for Cloudflare D1, simplifying database interactions.\n\n## Getting started with this project\n\n### Prerequisites\nBefore you begin, ensure you have the following installed:\n- Node.js (v16 or later)\n- npm (comes with Node.js)\n- Wrangler CLI (Cloudflare's command-line tool for Workers)\n\nIf you don't have Wrangler installed, you can install it globally via npm:\n```bash\nnpm install -g wrangler\n```\nYou'll also need a Cloudflare account.\n\nInstall the dependencies\n\n```bash\nnpm install\n```\n\nCreate a new D1 database (replace `\u003cyour-db-name\u003e` with a name of your choice):\n\n```bash\nwrangler d1 create \u003cyour-db-name\u003e\n```\n\nCopy the `database_id` and place it in the `wrangler.toml` file\n\n```toml\n[[d1_databases]]\nbinding = \"DB\"\ndatabase_name = \"\u003cyour-db-name\u003e\"\ndatabase_id = \"\u003cyour-db-id\u003e\"\n```\n\nApply initial migrations. These scripts set up the `users` and `users_sessions` tables required for storing user credentials and session information:\n\n```bash\n# Remote development\nwrangler d1 migrations apply DB --remote\n\n# Local development\nwrangler d1 migrations apply DB --local\n```\n\nStart the project\n\n```bash\nnpm run serve\n```\n\nNow open your browser at [http://localhost:8787/](http://localhost:8787/)\n\n## Project Structure\nA brief overview of important files and directories:\n- `src/`: Contains the core application code.\n    - `endpoints/`: Defines the API route handlers.\n    - `foundation/`: Includes foundational code like authentication logic (`auth.ts`).\n    - `index.ts`: The entry point for the Worker, setting up routes.\n    - `types.d.ts`: TypeScript type definitions.\n- `migrations/`: SQL files for D1 database migrations.\n- `wrangler.toml`: Configuration file for Cloudflare Workers, including D1 database bindings.\n- `package.json`: Project dependencies and scripts.\n- `README.md`: This file, providing information about the project.\n\n## Available Endpoints\nThis example application exposes the following API endpoints:\n- `POST /register`: Allows new users to register. Requires `name`, `email`, and `password` in the request body.\n- `POST /login`: Allows existing users to log in. Requires `email` and `password` in the request body. Returns a session token.\n- `GET /search`: An example protected endpoint that requires a valid Bearer token (obtained from login) in the `Authorization` header. It searches GitHub repositories based on a query parameter `q`.\n\nThe authentication logic (registration, login, and token validation) is detailed in the 'Authentication Flow' diagram below.\n\n## Authentication Flow\n\n```mermaid\nsequenceDiagram\n    participant Client\n    participant Server\n    participant Database\n\n    Client-\u003e\u003eServer: POST /register (name, email, password)\n    Server-\u003e\u003eServer: Hash password\n    Server-\u003e\u003eDatabase: INSERT user (name, email, hashedPassword)\n    alt User already exists\n        Server--\u003e\u003eClient: 400 Bad Request (User with that email already exists)\n    else User created successfully\n        Server--\u003e\u003eClient: 200 OK (User details)\n    end\n\n    Client-\u003e\u003eServer: POST /login (email, password)\n    Server-\u003e\u003eServer: Hash password\n    Server-\u003e\u003eDatabase: SELECT user (email, hashedPassword)\n    alt User not found or password incorrect\n        Server--\u003e\u003eClient: 400 Bad Request (Unknown user)\n    else User found and password correct\n        Server-\u003e\u003eServer: Generate session token\n        Server-\u003e\u003eDatabase: INSERT session (user_id, token, expires_at)\n        Server--\u003e\u003eClient: 200 OK (Session token)\n    end\n\n    Client-\u003e\u003eServer: GET /search (Authorization: Bearer token)\n    Server-\u003e\u003eDatabase: SELECT session (token, expires_at)\n    alt Invalid or expired token\n        Server--\u003e\u003eClient: 401 Unauthorized (Authentication error)\n    else Valid token\n        Server-\u003e\u003eServer: Process request (e.g., search GitHub)\n        Server--\u003e\u003eClient: 200 OK (Search results)\n    end\n```\n\n## License\nThis project is licensed under the MIT License. See the [LICENSE](LICENSE) file for details.\n\n## Screenshots\n\nSwagger interface: Demonstrates the auto-generated API documentation via Chanfana, showing available endpoints.\n![Swagger interface](https://github.com/G4brym/authentication-using-d1-example/raw/main/docs/swagger.png)\n\nUnauthenticated: Example of an error response when trying to access a protected endpoint without valid authentication.\n![Unauthenticated](https://github.com/G4brym/authentication-using-d1-example/raw/main/docs/unauthenticated.png)\n\nAuthentication: Shows a successful login response, including the session token.\n![Authentication](https://github.com/G4brym/authentication-using-d1-example/raw/main/docs/authentication.png)\n\nEndpoint results: An example of successfully accessing a protected endpoint (`/search`) after authenticating.\n![Endpoint results](https://github.com/G4brym/authentication-using-d1-example/raw/main/docs/results.png)\n","funding_links":[],"categories":["Templates \u0026 Examples"],"sub_categories":["Example Applications"],"project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2FG4brym%2Fauthentication-using-d1-example","html_url":"https://awesome.ecosyste.ms/projects/github.com%2FG4brym%2Fauthentication-using-d1-example","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2FG4brym%2Fauthentication-using-d1-example/lists"}