Skip to content

Latest commit

 

History

History
426 lines (326 loc) · 18.7 KB

README.md

File metadata and controls

426 lines (326 loc) · 18.7 KB

CI Coverage Status

nextjs-fastapi-template

Table of Contents

About

This template streamlines building APIs with FastAPI and dynamic frontends with Next.js. It integrates the backend and frontend using @hey-api/openapi-ts to generate a type-safe client, with automated watchers to keep the OpenAPI schema and client updated, ensuring a smooth and synchronized development workflow.

  • Next.js: Fast, SEO-friendly frontend framework
  • FastAPI: High-performance Python backend
  • SQLAlchemy: Powerful Python SQL toolkit and ORM
  • PostgreSQL: Advanced open-source relational database
  • Pydantic: Data validation and settings management using Python type annotations
  • Zod + TypeScript: End-to-end type safety and schema validation
  • fastapi-users: Complete authentication system with:
    • Secure password hashing by default
    • JWT (JSON Web Token) authentication
    • Email-based password recovery
  • Shadcn/ui: Beautiful and customizable React components
  • OpenAPI-fetch: Fully typed client generation from OpenAPI schema
  • fastapi-mail: Efficient email handling for FastAPI applications
  • Poetry: Dependency management and packaging made easy
  • Pytest: Powerful Python testing framework
  • Code Quality Tools:
    • Ruff: Fast Python linter
    • ESLint: JavaScript/TypeScript code quality
  • Hot reload watchers:
    • Backend: Watchdog for monitoring file changes
    • Frontend: Chokidar for live updates
  • Docker and Docker Compose: Consistent environments for development and production
  • MailHog: Email server for development
  • Pre-commit hooks: Enforce code quality with automated checks
  • OpenAPI JSON schema: Centralized API documentation and client generation

With this setup, you'll save time and maintain a seamless connection between your backend and frontend, boosting productivity and reliability.

Production-Ready Authentication & Dashboard features

This template comes with a pre-configured authentication system and a simple dashboard interface, allowing you to start building your application with user management features right away.

Getting Started with This Template

To use this template for your own project:

  1. Create a new repository using this template by following GitHub's template repository guide
  2. Clone your new repository and navigate to it: cd your-project-name
  3. Update this README:
    • Change the project name in the first line
    • Remove this "Getting Started with This Template" section
  4. Make sure you have Python 3.12 installed

Once completed, proceed to the Setup section below.

Setup

Installing Required Tools

1. Poetry

Poetry is used to manage Python dependencies in the backend. Install Poetry by following the official installation guide.

2. Node.jsm, npm and pnpm

Ensure Node.js and npm are installed for running the frontend. Follow the Node.js installation guide. After that install pnpm by running:

npm install -g pnpm

3. Docker

Docker is needed to run the project in a containerized environment. Follow the appropriate installation guide:

4. Docker Compose

Ensure docker-compose is installed. Refer to the Docker Compose installation guide.

Setting Up Environment Variables

Backend (fastapi_backend/.env): Copy the .env.example files to .env and update the variables with your own values.

cd fastapi_backend && cp .env.example .env
  1. You will only need to update the secret keys. You can use the following command to generate a new secret key:
    python3 -c "import secrets; print(secrets.token_hex(32))"
  2. The DATABASE, MAIL, OPENAPI, CORS, and FRONTEND_URL settings are ready to use locally.
  3. You can check the .env.example file for more information about the variables.

Frontend (nextjs-frontend/.env.local): Copy the .env.example files to .env. These values are unlikely to change, so you can leave them as they are.

cd nextjs-frontend && cp .env.example .env

Running the Database

  1. Use Docker to run the database to avoid local installation issues. Build and start the database container:
    docker compose build db
    docker compose up db
  2. Run the following command to apply database migrations:
    make docker-migrate-db

Build the project (without Docker):

To setup the project environment locally, use the following commands:

Backend

  1. Navigate to the fastapi_backend directory and run:
    poetry install

Frontend

  1. Navigate to the nextjs-frontend directory and run:
    pnpm install

Build the project (with Docker):

  1. Build the backend and frontend containers:
    make docker-build-backend
    make docker-build-frontend

Running the Application

If you are not using Docker:

  1. Start the FastAPI server:

    make start-backend
  2. Start the Next.js development server:

    make start-frontend

If you are using Docker:

  1. Start the FastAPI server container:
    make docker-up-backend
  2. Start the Next.js development server container:
    make docker-up-frontend
  • Backend: Access the API at http://localhost:8000.
  • Frontend: Access the web application at http://localhost:3000.

Hot Reload on development

The project includes two hot reloads when running the application, one for the backend and one for the frontend, which automatically restart local servers when they detect changes. This ensures that the application is always up-to-date without needing manual restarts.

  • The backend hot reload monitors changes to the backend code.
  • The frontend hot reload monitors changes to the frontend code, as well as to the openapi.json schema generated by the backend.

Manual Execution of Hot Reload Commands

You can manually execute the same commands that the hot reloads call when they detect a change:

  1. To export the openapi.json schema:

    cd fastapi_backend && poetry run python -m app.commands.generate_openapi_schema

    or using Docker:

    docker compose run --rm --no-deps -T backend poetry run python -m app.commands.generate_openapi_schema
  2. To generate the frontend client:

    cd nextjs-frontend && npm run generate-client

    or using Docker:

    docker compose run --rm --no-deps -T frontend npm run generate-client

Testing

To run the tests, you need to run the test database container:

make docker-up-test-db

Then run the tests locally:

make test-backend
make test-frontend

Or using Docker:

make docker-test-backend
make docker-test-frontend

Pre-Commit Setup

To maintain code quality and consistency, the project includes two separate pre-commit configuration files:

  • .pre-commit-config.yaml for running pre-commit checks locally.
  • .pre-commit-config.docker.yaml for running pre-commit checks within Docker.

Installing and Activating Pre-Commit Hooks

To activate pre-commit hooks, run the following commands for each configuration file:

  • For the local configuration file:

    pre-commit install -c .pre-commit-config.yaml
  • For the Docker configuration file:

    pre-commit install -c .pre-commit-config.docker.yaml

Email Localhost Setup

To setup the email locally, you need to start MailHog by running the following command:

make docker-up-mailhog
  • Email client: Access the email at http://localhost:8025.

Running Pre-Commit Checks

To manually run the pre-commit checks on all files, use:

pre-commit run --all-files -c .pre-commit-config.yaml

or

pre-commit run --all-files -c .pre-commit-config.docker.yaml

Updating Pre-Commit Hooks

To update the hooks to their latest versions, run:

pre-commit autoupdate

Alembic Database Migrations

If you need to create a new Database Migration:

make docker-db-schema migration_name="add users"

then apply the migration to the database:

make docker-migrate-db

GitHub Actions

This project comes with a pre-configured GitHub Actions setup to enable CI/CD. You can find the workflow configuration files inside the .github/workflows directory. Feel free to customize these workflows to better suit your project's needs.

Secrets Configuration

For the workflows to function correctly, make sure to add the necessary secret keys to your GitHub repository's settings. Navigate to Settings > Secrets and variables > Actions and add the following keys:

DATABASE_URL: The connection string for your primary database.
TEST_DATABASE_URL: The connection string for your test database.
ACCESS_SECRET_KEY: The secret key for access token generation.
RESET_PASSWORD_SECRET_KEY: The secret key for reset password functionality.
VERIFICATION_SECRET_KEY: The secret key for email or user verification.

Production Deployment

Overview

Deploy to Vercel is supported, with dedicated buttons for the Frontend and Backend applications. Both require specific configurations during and after deployment to ensure proper functionality.


Frontend Deployment

Deploy with Vercel

  1. Deploying the Frontend

    • Click the Frontend button above to start the deployment process.
    • During deployment, you will be prompted to set the API_BASE_URL. Use a placeholder value (e.g., https://) for now, as this will be updated with the backend URL later.
    • Complete the deployment process.
  2. Post-Deployment Configuration

    • Navigate to the Settings page of the deployed frontend project.
    • Access the Environment Variables section.
    • Update the API_BASE_URL variable with the backend URL once the backend deployment is complete.

Backend Deployment

Deploy with Vercel

  1. Deploying the Backend

    • Click the Backend button above to begin deployment.

    • During the deployment process, you will be prompted to configure the following environment variables:

      • CORS_ORIGINS

        • Set this to ["*"] initially to allow all origins. You will update this with the frontend URL later.
      • DATABASE_URL

        • Use a placeholder value (e.g., https://) if you don't yet have the actual database URL. Replace it with the correct URL post-deployment.
      • ACCESS_SECRET_KEY, RESET_PASSWORD_SECRET_KEY, VERIFICATION_SECRET_KEY

        • You can temporarily set these secret keys as plain strings (e.g., examplekey) during deployment. However, you should generate secure keys and update them after the deployment in the Post-Deployment Configuration section.
    • Complete the deployment process.

  2. Post-Deployment Configuration

    • Access the Settings page of the deployed backend project.

    • Navigate to the Environment Variables section and update the following variables with secure values:

      • CORS_ORIGINS

        • Once the frontend is deployed, replace ["*"] with the actual frontend URL.
      • DATABASE_URL

        • Update this with the actual database URL if not set during deployment.
      • ACCESS_SECRET_KEY

        • Generate a secure key for API access and set it here.
      • RESET_PASSWORD_SECRET_KEY

        • Generate a secure key for password reset functionality and set it.
      • VERIFICATION_SECRET_KEY

        • Generate a secure key for user verification and configure it.
    • For detailed instructions on how to set these secret keys, refer to the section on Setting up Environment Variables.

  3. Database Connection

    1. Choosing a Database

      • You can use your own database hosted on a different service or opt for the Neon database, which integrates seamlessly with Vercel.
    2. Setting Up a Neon Database via Vercel

      • In the Backend project page on Vercel, navigate to the Storage section.
      • Select the option to Create a Database to provision a Neon database.
    3. Configuring the Database URL

      • After creating the database, retrieve the Database URL provided by Neon.
      • Include this URL in your Environment Variables under DATABASE_URL.
      • Replace postgres with postgres+asyncpg at the start of the URL to ensure compatibility with asynchronous database operations.
    4. Migrating the Database

      • Once the database URL is configured, run your database migration script. This step is essential for creating the necessary tables and initializing your database schema.

Makefile

This project includes a Makefile that provides a set of commands to simplify common tasks such as starting the backend and frontend servers, running tests, building Docker containers, and more.

Available Commands

You can see all available commands and their descriptions by running the following command in your terminal:

make help

Important Considerations

  • Environment Variables: Ensure your .env files are up-to-date.
  • Database Setup: It is recommended to use Docker for running the database, even when running the backend and frontend locally, to simplify configuration and avoid potential conflicts.
  • Consistency: It is not recommended to switch between running the project locally and using Docker, as this may cause permission issues or unexpected problems. Choose one method and stick with it.

Contributing

If you wish to contribute to this project, please first discuss the change you wish to make via an issue.

Check our contributing guide to learn more about our development process and how you can test your changes to the boilerplate.

Share your project!

You can use our template to kick-start your project or streamline your efforts in securing funding. Starting with a strong foundation can make your product more resilient and allow you to focus on what matters most: delivering value to your customers.

If our template has been part of your journey, we'd love to hear about it! Share your story with us, and we’ll help spread the word about your project through our social media channels, giving it a broader reach.

Send us an email at [email protected] telling us a bit more about how our template helped you boost your project.

Commercial Support

alt text

This project is maintained by Vinta Software and is used in products of Vinta's clients. We are always looking for exciting work! If you need any commercial support, feel free to get in touch: [email protected]