Skip to content

About

No description, website, or topics provided.

Resources

Stars

0 stars

Watchers

0 watching

Forks

Latest commit

 

History

2 Commits

Folders and files

NameName
Last commit message
Last commit date
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Fullstack GraphQL Authentication

A complete fullstack application with GraphQL API, React frontend, and JWT authentication using Prisma ORM and PostgreSQL.

🚀 Features

  • Backend: Node.js + Express + Apollo Server
  • Frontend: React + Apollo Client
  • Database: PostgreSQL with Prisma ORM
  • Authentication: JWT-based authentication
  • API: GraphQL with queries and mutations
  • Containerization: Docker & Docker Compose

📋 Prerequisites

  • Node.js (v16 or higher)
  • Docker and Docker Compose
  • Git

🛠️ Tech Stack

Backend

  • Node.js - Runtime environment
  • Express - Web framework
  • Apollo Server - GraphQL server
  • Prisma - Database ORM
  • PostgreSQL - Database
  • JWT - Authentication
  • bcrypt - Password hashing

Frontend

  • React - UI library
  • Apollo Client - GraphQL client
  • React Router - Client-side routing

🚀 Quick Start

Using Docker (Recommended)

  1. Clone the repository

    git clone <repository-url>
    cd fullstack-graphql-auth
  2. Start the application

    sudo docker compose up -d
  3. Access the application

Manual Setup

  1. Install dependencies

    # Backend
    cd backend
    npm install
    
    # Frontend
    cd ../frontend
    npm install
  2. Set up environment variables

    # Backend
    cd backend
    cp .env.example .env
    # Edit .env with your database URL and JWT secret
  3. Set up the database

    cd backend
    npx prisma generate
    npx prisma db push
  4. Start the servers

    # Terminal 1 - Backend
    cd backend
    npm start
    
    # Terminal 2 - Frontend
    cd frontend
    npm start

📊 Database Schema

User Model

model User {
  id        Int      @id @default(autoincrement())
  email     String   @unique
  password  String
  name      String?
  posts     Post[]
  createdAt DateTime @default(now())
  updatedAt DateTime @updatedAt
}

Post Model

model Post {
  id        Int      @id @default(autoincrement())
  title     String
  content   String?
  author    User     @relation(fields: [authorId], references: [id])
  authorId  Int
  createdAt DateTime @default(now())
  updatedAt DateTime @updatedAt
}

🔌 GraphQL API

Queries

Get All Posts

query GetAllPosts {
  posts {
    id
    title
    content
    createdAt
    author {
      id
      name
      email
    }
  }
}

Get Current User

query GetMe {
  me {
    id
    email
    name
    posts {
      id
      title
      content
    }
  }
}

Get Specific Post

query GetPost($id: Int!) {
  post(id: $id) {
    id
    title
    content
    createdAt
    author {
      id
      name
      email
    }
  }
}

Mutations

Register User

mutation RegisterUser {
  register(
    email: "[email protected]"
    password: "password123"
    name: "John Doe"
  ) {
    token
    user {
      id
      email
      name
    }
  }
}

Login User

mutation LoginUser {
  login(email: "[email protected]", password: "password123") {
    token
    user {
      id
      email
      name
    }
  }
}

Create Post (Requires Authentication)

mutation CreatePost {
  createPost(
    title: "My First Post"
    content: "This is the content of my post"
  ) {
    id
    title
    content
    createdAt
    author {
      id
      name
    }
  }
}

Update Post (Requires Authentication + Ownership)

mutation UpdatePost {
  updatePost(id: 1, title: "Updated Title", content: "Updated content") {
    id
    title
    content
    updatedAt
  }
}

Delete Post (Requires Authentication + Ownership)

mutation DeletePost {
  deletePost(id: 1)
}

🔐 Authentication

The application uses JWT (JSON Web Tokens) for authentication:

  1. Register or Login to get a JWT token
  2. Include the token in the Authorization header for protected operations:
    Authorization: Bearer YOUR_JWT_TOKEN
    

Protected Operations

  • createPost - Create a new post
  • updatePost - Update an existing post
  • deletePost - Delete a post
  • me - Get current user info

🧪 Testing the API

Using Apollo GraphQL Sandbox

  1. Open Apollo GraphQL Sandbox
  2. Enter your GraphQL endpoint: http://localhost:4000/graphql
  3. Test queries and mutations

Using curl

# Test a simple query
curl -X POST http://localhost:4000/graphql \
  -H "Content-Type: application/json" \
  -d '{"query":"{ posts { id title } }"}'

# Test with authentication
curl -X POST http://localhost:4000/graphql \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer YOUR_JWT_TOKEN" \
  -d '{"query":"mutation { createPost(title: \"Test\", content: \"Content\") { id title } }"}'

🐳 Docker Commands

# Start all services
sudo docker compose up -d

# View logs
sudo docker compose logs -f

# Stop all services
sudo docker compose down

# Rebuild and start
sudo docker compose up --build -d

# Access database
sudo docker compose exec postgres psql -U postgres -d mydb

📁 Project Structure

fullstack-graphql-auth/
├── backend/
│   ├── src/
│   │   ├── index.js          # Server entry point
│   │   ├── schema.js         # GraphQL schema
│   │   ├── resolvers.js      # GraphQL resolvers
│   │   └── context.js        # GraphQL context
│   ├── prisma/
│   │   └── schema.prisma     # Database schema
│   ├── Dockerfile
│   └── package.json
├── frontend/
│   ├── src/
│   │   ├── pages/            # React pages
│   │   ├── App.js           # Main App component
│   │   ├── apollo.js        # Apollo Client setup
│   │   └── index.js         # React entry point
│   ├── Dockerfile
│   └── package.json
├── docker-compose.yml
├── .gitignore
└── README.md

🔧 Environment Variables

Backend (.env)

DATABASE_URL="postgresql://postgres:postgres@localhost:5432/mydb?schema=public"
JWT_SECRET="your-super-secret-jwt-key"
PORT=4000

🚀 Deployment

Using Docker Compose

  1. Production environment variables

    # Set production environment variables
    export NODE_ENV=production
    export JWT_SECRET=your-production-secret
    export DATABASE_URL=your-production-database-url
  2. Deploy with Docker Compose

    sudo docker compose -f docker-compose.prod.yml up -d

🤝 Contributing

  1. Fork the repository
  2. Create a feature branch (git checkout -b feature/amazing-feature)
  3. Commit your changes (git commit -m 'Add some amazing feature')
  4. Push to the branch (git push origin feature/amazing-feature)
  5. Open a Pull Request

📝 License

This project is licensed under the MIT License - see the LICENSE file for details.

🆘 Troubleshooting

Common Issues

  1. "Failed to fetch" error in GraphQL Playground

    • Check if the backend server is running
    • Verify CORS configuration
    • Ensure the correct endpoint URL
  2. "Not authenticated" error

    • Make sure you're including the Authorization header
    • Verify the JWT token is valid and not expired
    • Check if you're logged in first
  3. Database connection issues

    • Ensure PostgreSQL is running
    • Check the DATABASE_URL in your environment variables
    • Run npx prisma db push to sync the schema
  4. Docker issues

    • Check if Docker is running
    • Try rebuilding containers: sudo docker compose up --build -d
    • Check logs: sudo docker compose logs

📞 Support

If you encounter any issues or have questions, please:

  1. Check the troubleshooting section above
  2. Search existing issues in the repository
  3. Create a new issue with detailed information about your problem

Happy coding! 🎉

About

No description, website, or topics provided.

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages