This repository contains a simple backend application built with Express and TypeScript. The API provides user authentication and CRUD operations for posts. It uses PostgreSQL as the database and Prisma as the ORM.
- User registration and login with JWT-based authentication
- Protected routes for creating, updating and deleting posts
- Public endpoints to view posts
- Prisma schema for
UserandPostmodels
- Node.js (v16 or later recommended)
- PostgreSQL database
- npm or yarn
-
Clone the repository
git clone <repo-url> cd backend-2
-
Install dependencies
npm install # or yarn install -
Database configuration
Edit the
.envfile at the project root and set theDATABASE_URLvalue to point to your PostgreSQL instance. Example:DATABASE_URL="postgresql://postgres:postgres@localhost:5432/shop"
-
Generate Prisma client and run migrations
npx prisma generate npx prisma migrate dev --name init
-
Set JWT secret (optional)
By default the code uses a hardcoded secret (
"secret"). To use a custom value, set theJWT_SECRETenvironment variable:export JWT_SECRET="your_secret_here"
-
Start the development server
npm run dev
The server will listen on
http://localhost:3000.
-
POST /api/auth/register- Request body:
{ username, email, password } - Registers a new user.
- Request body:
-
POST /api/auth/login- Request body:
{ email, password } - Returns a JWT token and user details.
- Request body:
-
POST /api/auth/logout- No body required. Endpoint responds with confirmation; token invalidation is handled by the client.
GET /api/posts– returns a list of all posts with author info.GET /api/posts/:id– returns a single post.POST /api/posts– create a new post (requiresAuthorization: Bearer <token>).PUT /api/posts/:id– update a post (token of the author required).DELETE /api/posts/:id– delete a post (token of the author required).
- Passwords are hashed with bcrypt before storage.
- JWTs expire after 1 hour.
- The
authmiddleware checks theAuthorizationheader and attaches the user payload to the request.
Feel free to extend the project with additional models, routes, or middleware as needed.