Skip to content

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

bash
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 back
bash
npm install prisma --save-dev
npx prisma init
npm install @prisma/client
npm install @prisma/adapter-d1

TIP

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.

ts
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

bash
npx wrangler d1 create test_backend

4. Update DB binding in wrangler.jsonc

json
 "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

bash
# 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.sql

6. Run the migration

bash
# 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 generate

7. Generate types for working with D1

TIP

In order to query your database from the D1 database using Prisma, you need to add types:

bash
npx wrangler types

This 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

  1. Update Prisma Schema:

    • Add a hashedPassword field to the User model in prisma/schema.prisma.
    prisma
    model User {
      id             String @id @default(uuid())
      email          String @unique
      name           String?
      hashedPassword String // Add this line
    }
  2. 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 generate
  3. Install 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
  4. Configure JWT Secret:

    • Add a JWT_SECRET variable to your wrangler.toml for 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"
  5. 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 sign function from hono/jwt.
  6. Implement JWT Middleware:

    • Use Hono's jwt middleware to protect specific routes (e.g., a /api/profile route). Configure the middleware with your JWT_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 })
    })
  7. 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.

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.

Released under the MIT License.