Techstack v1
Frontend
Aktualnie projekt zbudowany na bazie:
- Framework: Next.js (React 19)
- Language: TypeScript
- Deployment: Cloudflare Workers
- Styling: Tailwind CSS with PostCSS
- UI Components: Radix UI (alternatywnie mogę Shadcn UI)
- Authentication: NextAuth.js
- Animation: Framer Motion
- Charts: Recharts
- State Management: React Context
Backend
Aktualnie backend jest zbudowany na:
- Runtime: Cloudflare Workers
- Language: TypeScript
- Framework: Hono.js
- Database: Cloudflare D1 (SQLite-based)
- Authentication: JWT
- Email: Resend
- Validation: Zod
Błędy jakie popełniłem
- Nie chcę używać Typescriptu w backendzie, chcę to zbudować na nowo
- Czy mogę połączyć backend w Pythonie z frontendem w Typescriptcie? Jak wtedy zaimplementować NextAuth?
- Brak automatycznych testów zarówno w backendzie jak i frontendzie
Testowanie backendu
- jak testować backend?
Automatyczne testowanie frontendu
- jak testować frontend?
- testy jednostkowe i integracyjne
Automatyczne testowanie backendu
- powinno używać wranglera do postawienia nowej instancji D1
- powinno uruchomić migracje korzystając z Prisma ORM
- powinno uruchomić
Techstack v2
Backend
Runtime: Cloudflare Workers
Deployment: Wrangler
Framework: Hono.js
ORM: Prisma + connector D1
Database: Cloudflare D1 (SQLite-based)
Validation: Zod
Testing: Jest
- alternatywnie: moze wystarczy Hono.js test runner
API: REST
Authentication: JWT? Probably
Email: Resend
Caching: Cloudflare Cache
Rate limiting: Cloudflare Rate Limiting
Milestone 1: Blank project with Hono.js, Prisma and D1
- Create a new Hono.js project
- Install Prisma and configure it to use Cloudflare D1
- Create a new D1 database
- Create a new Prisma schema
- Create a new migration
- Run the migration
- Create a new Hono.js route
- Test the route
- Create a new Prisma model
- Create a new Prisma migration
- Run the migration
TIP
Useful resources for Hono.js with Prisma and D1:
Required dependencies:
@prisma/adapter-d1@prisma/client
Steps
Below steps are based on hono.js prisma example with D1
1. Initialize new project with hono framework through wrangler
wrangler init
╭ Create an application with Cloudflare Step 1 of 3
│
╰ In which directory do you want to create your application?
dir /test
╰ What would you like to start with?
○ Hello World example
● Framework Starter
○ Application Starter
○ Template from a GitHub repo
◁ Go back
├ What would you like to start with?
│ category Framework Starter
│
╰ Which development framework do you want to use?
○ Analog
○ Angular
○ Astro
○ Docusaurus
○ Gatsby
● Hono
○ Next.js
○ Nuxt
○ Qwik
○ React
○ React Router (formerly Remix)
○ SolidStart
○ SvelteKit
○ Vue
◁ Go back2. Install Prisma and related dependencies
npm install prisma --save-dev
npx prisma init
npm install @prisma/client
npm install @prisma/adapter-d1TIP
After Prisma installation, it will generate schema for your database. Below is how to define a simple model in prisma/schema.prisma and change the adapter.
generator client {
provider = "prisma-client-js"
previewFeatures = ["driverAdapters"] // change from default
}
datasource db {
provider = "sqlite" // d1 is sql base database
url = env("DATABASE_URL")
}
// Create a simple model database
model User {
id String @id @default(uuid())
email String @unique
name String?
}3. Create new D1 database
npx wrangler d1 create test_backend4. Update DB binding in wrangler.jsonc
"d1_databases": [
{
"binding": "DB",
"database_name": "test_backend",
"database_id": "c0b26022-8309-4d84-bbc8-ad8c3fca2c73"
}
]5. Create database migrations
TIP
This command makes migrations for Prisma and changes to the D1 database, either local or remote
# Will generate a migration folder and SQL file
npx wrangler d1 migrations create test_backend create_user_table
# To generate SQL statement:
npx prisma migrate diff --from-empty --to-schema-datamodel ./prisma/schema.prisma --script --output migrations/0001_create_user_table.sql6. Run the migration
# Apply migration to local development database
npx wrangler d1 migrations apply test_backend --local
# Apply migration to remote production database
npx wrangler d1 migrations apply test_backend --remote
# Generate Prisma client
npx prisma generate7. Generate types for working with D1
TIP
In order to query your database from the D1 database using Prisma, you need to add types:
npx wrangler typesThis will generate a worker-configuration.d.ts file.
TIP
Working example available here
8. End of milestone 1
Milestone 2: User Authentication with JWT (AI generated)
- Implement user registration and login functionality.
- Secure endpoints using JSON Web Tokens (JWT).
Steps
Update Prisma Schema:
- Add a
hashedPasswordfield to theUsermodel inprisma/schema.prisma.
prismamodel User { id String @id @default(uuid()) email String @unique name String? hashedPassword String // Add this line }- Add a
Apply Migrations:
- Generate a new migration script for the schema change.
- Apply the migration to your local and remote D1 databases.
bash# Generate SQL diff for the new field npx prisma migrate diff --from-migrations ./migrations --to-schema-datamodel ./prisma/schema.prisma --script --output migrations/0002_add_user_password.sql # Apply migration locally npx wrangler d1 migrations apply test_backend --local # Apply migration remotely npx wrangler d1 migrations apply test_backend --remote # Regenerate Prisma Client npx prisma generateInstall Dependencies:
- Add a library for password hashing (e.g.,
bcryptjs) or plan to use the Web Crypto API available in Workers. Hono's JWT middleware is built-in.
bash# Example using bcryptjs npm install bcryptjs npm install --save-dev @types/bcryptjs- Add a library for password hashing (e.g.,
Configure JWT Secret:
- Add a
JWT_SECRETvariable to yourwrangler.tomlfor local development and configure it in your Cloudflare Worker secrets for production.
toml# wrangler.toml [vars] JWT_SECRET = "your-super-secret-key-for-local-dev"- Add a
Implement Authentication Logic:
- Create Hono routes for user registration (
/api/register) and login (/api/login). - Registration: Hash the user's password before saving it to the database using Prisma.
- Login: Retrieve the user by email, compare the provided password with the stored hash, and if valid, generate a JWT using Hono's
signfunction fromhono/jwt.
- Create Hono routes for user registration (
Implement JWT Middleware:
- Use Hono's
jwtmiddleware to protect specific routes (e.g., a/api/profileroute). Configure the middleware with yourJWT_SECRET.
typescript// Example in src/index.ts or relevant route file import { Hono } from 'hono' import { jwt } from 'hono/jwt' // ... other imports and app setup app.use('/api/profile/*', async (c, next) => { const jwtMiddleware = jwt({ secret: c.env.JWT_SECRET, }) return jwtMiddleware(c, next) }) app.get('/api/profile', (c) => { const payload = c.get('jwtPayload') // Use payload.userId (or whatever you included) to fetch user data return c.json({ message: 'This is a protected route', user: payload }) })- Use Hono's
Testing:
- Add tests (using Hono's test client or Jest) to verify:
- Successful user registration.
- Successful login and JWT issuance.
- Rejection of invalid login credentials.
- Access denied to protected routes without a valid JWT.
- Access granted to protected routes with a valid JWT.
- Add tests (using Hono's test client or Jest) to verify:
Milestone 3: Frontend Integration (Placeholder)
- Connect Next.js frontend.
- Implement UI for login/registration.
- Use NextAuth.js on the frontend, potentially configuring it to use the Hono JWT backend via a Credentials provider or by adapting the backend to support NextAuth's expected OAuth/callback flows if needed.