Skip to content

State of the art project template that integrates Next.js, Zod, FastAPI for full-stack TypeScript + Python projects.

License

Notifications You must be signed in to change notification settings

vintasoftware/nextjs-fastapi-template

Repository files navigation

Next.js FastAPI Template

Next.js FastAPI Template: Python + Modern TypeScript stack with Zod validation.

CI Coverage


Source Code: https://github.com/vintasoftware/nextjs-fastapi-template


Next.js FastAPI Template

Introducing the Next.js FastAPI Template: A cutting-edge foundation for modern full-stack development that seamlessly integrates Next.js with FastAPI. This template combines Python's backend power with TypeScript's frontend, enhanced by Zod's robust type validation. Perfect for developers seeking a production-ready architecture that balances performance, type safety, and developer experience in one cohesive package.

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
  • uv: An extremely fast Python package and project manager
  • 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 immediately.

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. uv

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

2. Node.jsm, npm and pnpm

To run the frontend, ensure Node.js and npm are installed. 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. The DATABASE and MAIL settings are already configured in Docker Compose if you're using Docker.
  4. The OPENAPI_URL setting is commented out. Uncommenting it will hide the /docs and openapi.json URLs, which is ideal for production.
  5. 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 -d db
  2. Run the following command to apply database migrations:
    make docker-migrate-db

Build the project (without Docker):

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

Backend

  1. Navigate to the fastapi_backend directory and run:
    uv sync

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

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-start-backend
  2. Start the Next.js development server container:
    make docker-start-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 running the application, one for the backend and one for the frontend. These automatically restart local servers when they detect changes, ensuring 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 and 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 && uv run python -m commands.generate_openapi_schema

    or using Docker:

    docker compose run --rm --no-deps -T backend uv run python -m 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 is used to run pre-commit checks locally.
  • .pre-commit-config.docker.yaml is used to run 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

Localhost Email Server Setup

To set up the email server 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 has a pre-configured GitHub Actions setup to enable CI/CD. The workflow configuration files are inside the .github/workflows directory. You can customize these workflows to suit your project's needs better.

Secrets Configuration

For the workflows to function correctly, add the 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

Deploying 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 here.

Backend Deployment

Deploy with Vercel

  1. Deploying the Backend
    • Click the Backend button above to begin deployment.

    • First, set up the database. The connection is automatically configured, so follow the steps, and it should work by default.

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

      • CORS_ORIGINS

        • Set this to ["*"] initially to allow all origins. Later, you can update this with the frontend URL.
      • ACCESS_SECRET_KEY, RESET_PASSWORD_SECRET_KEY, VERIFICATION_SECRET_KEY

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

CI (GitHub Actions) Setup for Production Deployment

We provide the prod-backend-deploy.yml and prod-frontend-deploy.yml files to enable continuous integration through Github Actions. To connect them to GitHub, simply move them to the .github/workflows/ directory.

You can do it with the following commands:

 mv prod-backend-deploy.yml .github/workflows/prod-backend-deploy.yml
 mv prod-frontend-deploy.yml .github/workflows/prod-frontend-deploy.yml

Prerequisites

  1. Create a Vercel Token:

  2. Install Vercel CLI:

    pnpm i -g vercel@latest
  3. Authenticate your account.

    vercel login

Database Creation (Required)

  1. Choosing a Database

    • You can use your 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 Projects dashboard 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.
  4. Migrating the Database

    • The database migration will happen automatically during the GitHub action deployment, setting up the necessary tables and schema.

Frontend Setup

  1. Link the nextjs-frontend Project

  2. Navigate to the nextjs-frontend directory and run:

    cd nextjs-frontend
    vercel link
  3. Follow the prompts:

    • Link to existing project? No
    • Modify settings? No
  4. Save Project IDs and Add GitHub Secrets:

  • Open nextjs-frontend/.vercel/project.json and add the following to your GitHub repository secrets:
    • projectIdVERCEL_PROJECT_ID_FRONTEND
    • orgIdVERCEL_ORG_ID

Backend Setup

  1. Link the fastapi_backend Project

  2. Navigate to the fastapi_backend directory and run:

    cd fastapi_backend
    vercel link --local-config=vercel.prod.json
    • We use a specific configuration file to set the --local-config value.
  3. Follow the prompts:

    • Link to existing project? No
    • Modify settings? No
  4. Save Project IDs and Add GitHub Secrets:

  • Open fastapi_backend/.vercel/project.json and add the following to your GitHub repository secrets:
    • projectIdVERCEL_PROJECT_ID_BACKEND
    • orgIdVERCEL_ORG_ID (Only in case you haven't added that before)

Notes

  • Once everything is set up, run git push, and the deployment will automatically occur.
  • Please ensure you complete the setup for both the frontend and backend separately.
  • Refer to the Vercel CLI Documentation for more details.
  • You can find the project_id into the vercel web project settings.
  • You can find the organization_id into the vercel web organization settings.

Post-Deployment Configuration

Frontend

  • 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

  • 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.
    • 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 setting these secret keys, please look at the section on Setting up Environment Variables.

Fluid serverless activation

Fluid is Vercel's new concurrency model for serverless functions, allowing them to handle multiple requests per execution instead of spinning up a new instance for each request. This improves performance, reduces cold starts, and optimizes resource usage, making serverless workloads more efficient.

Follow this guide to activate Fluid.

Makefile

This project includes a Makefile that provides a set of commands to simplify everyday 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 to run 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. You can choose one method and stick with it.

Contributing

If you wish to contribute to this project, please discuss the change you want 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 to secure 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.

Please email us at [email protected] telling us 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]