# Introduction
URL: /docs
Zap.ts - Build applications as fast as a zap.
***
title: Introduction
description: Zap.ts - Build applications as fast as a zap.
----------------------------------------------------------
# Welcome to Zap.ts
**Zap.ts** is a **Next.js** boilerplate designed to help you build applications *faster* using a modern set of tools. It comes with best practices to build *excellent* modern web applications.
## Getting Started
Ready to build something amazing? Start with our [installation guide](/docs/introduction/installation) or explore the [plugins overview](/docs/plugins/overview) to see what's possible.
***
*Built with ❤️ by [Alexandre Trotel](https://www.alexandretrotel.org) and many other **contributors**.*
# Model Context Protocols (MCPs)
URL: /docs/ai-powered-ide/mcps
Learn how to use MCPs to connect AI-powered editors to your services for enhanced development workflows.
***
title: Model Context Protocols (MCPs)
description: Learn how to use MCPs to connect AI-powered editors to your services for enhanced development workflows.
---------------------------------------------------------------------------------------------------------------------
# Model Context Protocols (MCPs)
[MCP (Model Context Protocol)](https://docs.cursor.com/context/model-context-protocol) allows **AI-powered editors** to connect AI directly to your services—whether it's *GitHub for pull requests*, *Supabase for databases*, or *PostHog for analytics*.
This turns the LLM from a passive assistant into an **active agent** that can interact with APIs, services, or CLIs.
## Built-In MCPs
Zap.ts comes preconfigured with the most commonly used services to save you setup time. These are defined in configuration files for each editor:
* **Cursor**: `.cursor/mcp.json`
* **VS Code**: `.vscode/mcp.json`
* **Windsurf**: `.windsurf/mcp.json`
Here are some of the built-in MCPs:
* [ElevenLabs](https://www.elevenlabs.io) — Use realistic text-to-speech directly from your IDE.
* [Firecrawl](https://firecrawl.dev) — Crawl and extract structured data from websites.
* [GitHub](https://github.com) — Automate PRs, issues, and more.
* [Magic by 21st.dev](https://21st.dev/magic) — Secure authentication with a few lines of code.
* [Neon](https://neon.tech) — A modern Postgres platform, optimized for serverless.
* [Notion](https://www.notion.com) — Read and write structured Notion content via the API.
* [Perplexity](https://www.perplexity.ai) — Ask factual questions via API.
* [PostHog](https://posthog.com) — Analyze events, user sessions, and feature flags.
* [Resend](https://resend.com) — Send transactional emails with ease.
* [Sentry](https://sentry.io) — Monitor and manage application errors from inside Cursor.
* [Supabase](https://supabase.com) — Query and mutate your database directly.
Of course, you can customize them as you wish.
Many of these integrations rely on **environment variables** for API keys or tokens.
All MCP-related variables follow a naming convention: they are **prefixed with `MCP_`**.
Make sure to define them in your local `.env` file or shell environment.
**Example:**
```txt
MCP_POSTHOG_AUTH_HEADER=Bearer your_posthog_token
MCP_SUPABASE_ACCESS_TOKEN=your_supabase_token
```
# Overview
URL: /docs/ai-powered-ide/overview
Learn how Zap.ts integrates with AI-powered IDEs like Cursor, Windsurf, and VS Code to enhance your development experience.
***
title: Overview
description: Learn how Zap.ts integrates with AI-powered IDEs like Cursor, Windsurf, and VS Code to enhance your development experience.
----------------------------------------------------------------------------------------------------------------------------------------
# Overview
[**Cursor**](https://www.cursor.com/), [**Windsurf**](https://windsurf.com/) and [**Visual Studio Code**](https://code.visualstudio.com/) are AI-powered IDEs designed to help developers build *faster* by enhancing their workflow.
It offers features like [MCPs](https://modelcontextprotocol.io/overview) to streamline coding.
In this section, we'll explain what these features are and how Zap.ts integrates with **them** to boost your development experience.
However, we strongly recommend reviewing all AI-generated code carefully and avoiding blind *"vibe coding"*.
While Zap.ts provides a framework and best practices to guide LLMs, understanding your code remains essential.
**We are not responsible for any issues from unchecked AI output.**
# Create Projects
URL: /docs/cli/create-projects
Learn how to create new projects using the Zap.ts CLI.
***
title: Create Projects
description: Learn how to create new projects using the Zap.ts CLI.
-------------------------------------------------------------------
# Create Projects
The `create-zap-app` CLI is a tool for *quickly* setting up a Zap.ts project.
You can run `zap --help` to check the latest CLI available commands. But in the meantime, here is a *concise* overview of what the CLI does when installing your project.
## Creating a New Project
Running `create-zap-app` or `zap` without arguments sets up a new Zap.ts project.
The following steps are done to install the project:
1. Asks for a name (default: `my-zap-app`) and ensuring everything is okay.
2. Lets you choose your *favorite* package manager (e.g. `npm`, `yarn`, `pnpm`, or `bun`).
3. Fetches the Zap.ts template from GitHub and extracts it.
4. Installs dependencies using the selected package manager.
5. Creates an `.env.local` file with placeholders.
# Manage Projects
URL: /docs/cli/manage-projects
Learn how to manage existing projects using the Zap.ts CLI.
***
title: Manage Projects
description: Learn how to manage existing projects using the Zap.ts CLI.
------------------------------------------------------------------------
# Manage Existing Projects
## Create Procedures
The CLI can automatically generate procedure files, register them in your oRPC router, and create a React hook for easy data fetching. This ensures your codebase stays consistent and follows best practices.
For example, running `zap create procedure example` will:
1. **Create a procedure file** in `src/rpc/procedures/example.rpc.ts`:
```ts
import "server-only";
import { authMiddleware, base } from "@/rpc/middlewares";
import { withRpcHandler } from "@/zap/errors/handlers";
export const example = base.use(authMiddleware).handler(
withRpcHandler(({ context }) => {
// Access session or other context here
return { message: "Hello, World!" };
}),
);
```
2. **Register the procedure** in your router (`src/rpc/router.ts`):
```ts
import "server-only";
import { example } from "@/rpc/procedures/example.rpc";
export const router = {
example,
// ...other procedures
};
```
3. **Create a React hook** in `src/hooks/rpc/use-example.ts`:
```ts
"use client";
import "client-only";
import { useZapQuery } from "@/zap/api/hooks";
import { orpcQuery } from "@/zap/api/providers/orpc/client";
export function useExample() {
return useZapQuery(orpcQuery.example.queryOptions({}));
}
```
4. You can remove or customize the generated hook as needed.
For example, if it's a mutation, you would change the `useZapQuery` to `useZapMutation` and use the appropriate mutation options.
```ts
"use client";
import "client-only";
import { useZapMutation } from "@/zap/api/hooks";
import { orpcQuery } from "@/zap/api/providers/orpc/client";
export function useExample() {
return useZapMutation(orpcQuery.example.mutationOptions({}));
}
```
## Generate `.env.local` File
You can generate a starter environment file using the CLI:
1. Run the following command in your project directory:
```bash
zap generate env
```
This will create a file named `.env.template` (or `.env.local` if specified).
2. The generated file includes all required and optional environment variables, with example/default values for each. Secrets are auto-generated for fields like `BETTER_AUTH_SECRET` and `ENCRYPTION_KEY`.
3. Next steps:
* **Review and customize** the variables in `.env.template`.
* **Copy** `.env.template` to `.env.local` (or `.env`) in your project.
* **Fill in** the actual values for your environment.
* **Add** your environment file to `.gitignore` if it contains sensitive data.
Required variables must be set and uncommented while optional ones can remain commented. Finally, real secrets must never be committed to version control.
# Overview
URL: /docs/cli/overview
Understand how the CLI tools in Zap.ts enhance your development workflow.
***
title: Overview
description: Understand how the CLI tools in Zap.ts enhance your development workflow.
--------------------------------------------------------------------------------------
# Overview
Zap.ts includes a CLI tool that helps you manage your project with simple, powerful commands. The CLI is available via the `create-zap-app` npm package, which provides the aliases `zap` and `create-zap-app`.
When installed as a dev dependency, you can also run it using `npm run zap`.
## Installation
We recommend you to install the CLI globally for easier access, but you can also use it locally within your project.
```bash
npm install -g create-zap-app
```
```bash
yarn global add create-zap-app
```
```bash
pnpm add -g create-zap-app
```
```bash
bun add -g create-zap-app
```
## Usage
Whether you're starting a new project or maintaining an existing one, these tools are designed to enhance your workflow and improve your development experience.
# Architecture
URL: /docs/introduction/architecture
Here is the complete architecture of a Zap.ts application compared to a traditional Next.js application.
***
title: Architecture
description: Here is the complete architecture of a Zap.ts application compared to a traditional Next.js application.
---------------------------------------------------------------------------------------------------------------------
# Overview
Zap.ts architecture is designed to be modular, scalable, and easy to maintain. It leverages the power of TypeScript and modern web development practices to provide a robust foundation for building applications.
Since Zap.ts is built on top of [Next.js](https://nextjs.org/), it inherits all the features and benefits of the Next.js framework while introducing its own conventions and best practices.
Below, we will compare the architecture of a Zap.ts application with that of a traditional Next.js application.
## Dependency Overview
Zap.ts builds on top of Next.js, extending its classic dependencies and adding many more for enhanced features, developer experience, and scalability. Dependencies are grouped below for clarity.
### Classic Dependencies
* [`next`](https://nextjs.org/): The core React framework for server-side rendering, routing, and static site generation.
* [`react`](https://react.dev/): The foundational library for building user interfaces.
* [`react-dom`](https://react.dev/): Provides DOM-specific methods for React.
* [`tailwindcss`](https://tailwindcss.com/): Utility-first CSS framework for rapid UI development.
### Zap.ts Additional Dependencies
* [`@ai-sdk/openai`](https://ai-sdk.dev/providers/ai-sdk-providers/openai): Integrates OpenAI models for AI features.
* [`@ai-sdk/mistral`](https://ai-sdk.dev/providers/ai-sdk-providers/mistral): Integrates Mistral models for AI features.
* [`@ai-sdk/react`](https://ai-sdk.dev/docs/introduction): React bindings for AI SDK.
* [`@bprogress/next`](https://bprogress.vercel.app/): Progress bar for Next.js apps.
* [`@flags-sdk/posthog`](https://flags-sdk.dev/providers/posthog): Feature flags and analytics integration.
* [`@hookform/resolvers`](https://react-hook-form.com/docs/useform/#resolver): Validation resolvers for React Hook Form.
* [`@mdx-js/loader`, `@mdx-js/react`](https://mdxjs.com/): MDX integration for JSX in Markdown.
* [`@neondatabase/serverless`](https://neon.tech/): Serverless PostgreSQL driver for scalable DB access.
* [`@next/bundle-analyzer`](https://github.com/vercel/next.js/tree/canary/packages/next-bundle-analyzer): Bundle analysis for Next.js apps.
* [`@orpc/client`, `@orpc/react-query`, `@orpc/server`](https://orpc.unnoq.com/): oRPC for typed remote procedure calls and API integration.
* [`@polar-sh/better-auth`, `@polar-sh/sdk`](https://polar.sh/): Payment processing integrated with [Better Auth](https://better-auth.com/).
* [`@react-email/components`](https://react.email/): Build and send emails with React components.
* [`@tanstack/react-query`, `@tanstack/react-query-devtools`](https://tanstack.com/query/latest): Powerful data fetching and caching for React.
* [`@types/mdx`](https://www.npmjs.com/package/@types/mdx): TypeScript types for MDX.
* [`@vercel/analytics`, `@vercel/speed-insights`](https://vercel.com/analytics): Analytics for Vercel-hosted apps and performance monitoring.
* [`ai`](https://ai-sdk.dev/): Vercel AI SDK for LLMs and generative AI features.
* [`better-auth`](https://better-auth.com/): Authentication solution for modern apps.
* [`class-variance-authority`](https://cva.style/): Utility for managing class names and variants in React.
* [`client-only`](https://nextjs.org/docs/app/getting-started/server-and-client-components#preventing-environment-poisoning): Next.js component for client-only rendering.
* [`clsx`](https://github.com/lukeed/clsx): Utility for constructing className strings conditionally.
* [`cmdk`](https://cmdk.paco.me/): Command menu component for React.
* [`date-fns`](https://date-fns.org/): Modern date utility library.
* [`dotenv`](https://www.dotenv.org/): Loads environment variables from `.env` files.
* [`drizzle-orm`](https://orm.drizzle.team/): TypeScript ORM for SQL databases, with migration and schema tools.
* [`embla-carousel-react`](https://www.embla-carousel.com/): Carousel component for React.
* [`flags`](https://flags-sdk.dev/): Feature flagging and remote config.
* [`gray-matter`](https://github.com/jonschlinkert/gray-matter): Parse front matter from Markdown files.
* [`input-otp`](https://input-otp.rodz.dev/): One-time password input component for React.
* [`lucide-react`](https://lucide.dev/): Icon library for React.
* [`motion`](https://motion.dev/): Animation library for React.
* [`next-mdx-remote`](https://github.com/hashicorp/next-mdx-remote): Load MDX content remotely in Next.js.
* [`next-sitemap`](https://github.com/iamvishnusankar/next-sitemap): Sitemap generation for Next.js apps.
* [`next-themes`](https://github.com/pacocoursey/next-themes): Theme switching for Next.js apps.
* [`nuqs`](https://nuqs.47ng.com/): Type-safe URL search params for React.
* [`pg`](https://node-postgres.com/): PostgreSQL client for Node.js.
* [`posthog-js`, `posthog-node`](https://posthog.com/): Analytics and event tracking.
* [`radix-ui`](https://www.radix-ui.com/): Primitives for building accessible UI components.
* [`react-day-picker`](https://react-day-picker.js.org/): Date picker component for React.
* [`react-email`](https://react.email/): Email templates and sending with React.
* [`react-hook-form`](https://react-hook-form.com/): Form management for React.
* [`react-resizable-panels`](https://react-resizable-panels.vercel.app/): Resizable panel UI for React.
* [`react-syntax-highlighter`](https://github.com/react-syntax-highlighter/react-syntax-highlighter): Syntax highlighting for code blocks.
* [`recharts`](https://recharts.org/): Charting library for React.
* [`resend`](https://resend.com/): Email sending service.
* [`schema-dts`](https://github.com/google/schema-dts): TypeScript types for schema.org.
* [`serialize-javascript`](https://github.com/yahoo/serialize-javascript): Serialize JS data for transfer.
* [`server-only`](https://nextjs.org/docs/app/getting-started/server-and-client-components#preventing-environment-poisoning): Next.js component for server-only rendering.
* [`sonner`](https://sonner.emilkowal.ski/): Toast notification library for React.
* [`tailwind-merge`](https://github.com/dcastil/tailwind-merge): Merge Tailwind CSS classes intelligently.
* [`tailwindcss-animate`](https://github.com/jamiebuilds/tailwindcss-animate): Animation utilities for Tailwind CSS.
* [`vaul`](https://vaul.emilkowal.ski/): Drawer component for React.
* [`web-push`](https://github.com/web-push-libs/web-push): Push notifications for web apps.
* [`zod`](https://zod.dev/): TypeScript-first schema validation.
* [`zustand`](https://zustand-demo.pmnd.rs/): State management for React.
### Classic Dev Dependencies
* [`@biomejs/biome`](https://biomejs.dev/): Fast linter and formatter for TypeScript/JavaScript.
* [`@tailwindcss/postcss`](https://tailwindcss.com/docs/installation/using-postcss): PostCSS plugin for Tailwind integration.
* `@types/*`: TypeScript type definitions for Node, React, etc.
* [`typescript`](https://www.typescriptlang.org/): Type-safe JavaScript development.
### Zap.ts Additional Dev Dependencies
* [`@react-email/preview-server`](https://react.email/): Development server for previewing React Email templates.
* [`create-zap-app`](https://zap-ts.alexandretrotel.org/docs/cli/overview): CLI for creating and managing Zap.ts projects.
* [`cross-env`](https://github.com/kentcdodds/cross-env): Run scripts that set and use environment variables across platforms.
* [`drizzle-kit`](https://orm.drizzle.team/docs/kit-overview#migrations-with-drizzle-kit): CLI for Drizzle ORM migrations and schema generation.
* [`react-scan`](https://react-scan.vercel.app/): Library to automatically detects performance issues in your React app.
* [`ultracite`](https://ultracite.ai/): AI-powered linter/formatter for collaborative coding between humans and AI.
Zap.ts also includes many dev tools and scripts for database management, email previews, code analysis, and more, making it a full-featured boilerplate for modern web apps.
## Files & Folders
In the below section, we explain all files and folders present in a typical Zap.ts project structure compared to a standard Next.js project. Next to each file, you'll find a color code (green, yellow, and red) indicating its status.
* 🟢 Added
* 🟡 Modified
* 🔴 Removed
### Root & Public
Removed [Vercel](https://vercel.com/) default files and added standard files for a better [SEO (Search Engine Optimization)](https://developers.google.com/search/docs/fundamentals/seo-starter-guide).
Added a service worker for [PWA (Progressive Web App)](https://nextjs.org/docs/app/guides/progressive-web-apps) support with [push notification](https://developer.mozilla.org/en-US/docs/Web/API/Push_API) capabilities.
Added custom fonts for the project such as [Geist](https://vercel.com/font).
Replaced default [Next.js](https://nextjs.org/) favicon with Zap.ts favicon.
Replaced default [Next.js](https://nextjs.org/) global styles by integrating [shadcn/ui](https://ui.shadcn.com/) styles by default and adding custom global styles.
Replaced default [Next.js](https://nextjs.org/) layout with a custom layout in Zap.ts with [shadcn/ui](https://ui.shadcn.com/) integration, [Geist](https://vercel.com/font) font, additional metadata for better [SEO (Search Engine Optimization)](https://developers.google.com/search/docs/fundamentals/seo-starter-guide), custom providers injection and [Vercel](https://vercel.com/) analytics support depending on the environment.
#### Metadata
Added Apple Touch Icon for better [SEO (Search Engine Optimization)](https://developers.google.com/search/docs/fundamentals/seo-starter-guide).
Configuration file for [Geist](https://vercel.com/font) font to be used in the application.
Added standard icon for better [SEO (Search Engine Optimization)](https://developers.google.com/search/docs/fundamentals/seo-starter-guide).
Dynamic Open Graph image generation route using [OG Image](https://og-image.vercel.app/) to create social media preview images on the fly.
Configuration file for the [Web App Manifest](https://developer.mozilla.org/en-US/docs/Web/Manifest) to provide metadata for the application when installed on a device or added to the home screen as a [PWA (Progressive Web App)](https://web.dev/progressive-web-apps/).
#### Error Handling
Global error handling component for the application with a sophisticated error messages management.
Beautiful custom 404 page for handling "Not Found" errors in the application.
#### IDE-Specific Files
Contains [MCP (Model Context Protocol)](https://modelcontextprotocol.io/) that allows LLMs in [Cursor](https://cursor.com/) to get more context with external services such as [Supabase](https://supabase.com/), [PostHog](https://posthog.com/), and more.
Similar to `.gitignore`, this file specifies which files and directories should be ignored by [Cursor](https://cursor.com/).
Contains [GitHub](https://github.com/) specific files such as workflows for CI/CD, instructions for [Copilot](https://github.com/features/copilot).
Contains [Visual Studio Code](https://code.visualstudio.com/) specific settings and configurations such as [MCP (Model Context Protocol)](https://modelcontextprotocol.io/), debugging configurations, and more.
Contains [Windsurf](https://windsurf.com/) specific settings and configurations such as [MCP (Model Context Protocol)](https://modelcontextprotocol.io/).
#### Docker Files
Similar to `.gitignore`, this file specifies which files and directories should be ignored by [Docker](https://www.docker.com/).
Contains the instructions for building a Docker image provisioning a [PostgreSQL](https://www.postgresql.org/) database along with the application.
Contains the instructions for building a Docker image for the application following [Next.js Docker best practices](https://github.com/vercel/next.js/tree/canary/examples/with-docker).
Contains the configuration for [Docker Compose](https://docs.docker.com/compose/) to define and run multi-container Docker applications (such as Zap.ts and PostgreSQL).
### Configurations
Configuration file for [Biome](https://biomejs.dev/), a linter and code formatter. We're using [Ultracite](https://ultracite.ai/) preset for better collaborations between AI and developers.
Configuration file for [Next.js](https://nextjs.org/) that includes additional settings for [CSP (Content Security Policy)](https://developer.mozilla.org/en-US/docs/Web/HTTP/CSP) and [Permissions Policy](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Permissions-Policy), sets up [Typed Routes](https://nextjs.org/docs/app/api-reference/config/next-config-js/typedRoutes) by default, adds extra [security headers](https://nextjs.org/docs/app/api-reference/config/next-config-js/headers), configures [sw.js](https://nextjs.org/docs/app/guides/progressive-web-apps#5-creating-a-service-worker), and supports [MDX](https://nextjs.org/docs/app/guides/mdx) along with [Bundle Analyzer](https://nextjs.org/docs/app/getting-started/linking-and-navigating#hydration-not-completed).
Configuration file for [npm](https://www.npmjs.com/) with additional scripts for [Biome](https://biomejs.dev/), [Drizzle ORM](https://orm.drizzle.team/), [Next.js](https://nextjs.org/), [React Email](https://react.email/) and more. Also includes [lint-staged](https://github.com/okonet/lint-staged) configuration with [Ultracite](https://ultracite.ai/) preset.
TypeScript configuration file with paths and settings optimized for Zap.ts such as `strictNullChecks`.
Configuration file for [shadcn/ui](https://ui.shadcn.com/), a set of accessible and customizable React components.
Configuration file for [Drizzle ORM](https://orm.drizzle.team/) in development mode.
Configuration file for [Drizzle ORM](https://orm.drizzle.team/) in production mode.
Configuration file for [next-sitemap](https://github.com/iamvishnusankar/next-sitemap), a sitemap generation tool for Next.js applications.
Specifies which files and directories should be ignored by [Git](https://git-scm.com/), modified to include additional files and directories.
### Pages
Added protected routes for authenticated users with a sidebar layout. This includes pages for account management, notifications, settings, and billing. Included pages are: `/app`, `/app/account` (WIP), `/app/notifications` (WIP), `/app/settings` (WIP).
Added billing routes for user billing information and a billing success page. Included pages are: `/app/billing`, `/app/billing/success`.
Added public authentication routes for user login, registration, password recovery, and mail verification. Included pages are: `/forgot-password`, `/login`, `/mail-verified`, `/register`, and `/reset-password`.
Added public legal routes for cookie policy, privacy policy, and terms of service. Included pages are: `/cookie-policy`, `/privacy-policy`, and `/terms-of-service`.
Added public blog routes for displaying blog posts and a blog landing page. This includes dynamic routing for individual blog posts based on their slug. Included pages are: `/blog`, `/blog/[slug]`.
Public landing page for the application.
Waitlist page for users to join the waitlist. Included pages are: `/waitlist`.
Default [Next.js](https://nextjs.org/) homepage, replaced by a custom homepage in Zap.ts.
### Routes
Authentication API route for handling all auth-related requests with [Better Auth](https://better-auth.com).
RPC API route for handling all RPC-related requests with [oRPC](https://orpc.unnoq.com).
### Components
Various UI components from [shadcn/ui](https://ui.shadcn.com/). Note that [Ultracite](https://ultracite.ai/) ignores this directory to keep original code as is.
### Hooks
Custom hook for detecting mobile devices and handling mobile-specific logic. This is needed by [shadcn/ui](https://ui.shadcn.com/).
Custom hook for managing body scroll locking in modals and other components.
Custom hook for implementing cooldowns on actions (e.g., mail ratelimits).
### Libraries
Custom fetch wrapper for making API requests with [Zod](https://zod.dev/) validation and error handling, it works in Edge and Node.js environments.
Plugin management library for handling Zap.ts plugins.
Utility functions such as `cn` (class names) that is needed by [shadcn/ui](https://ui.shadcn.com/).
### Emails
Contains email templates and allows for easy customization and management of email content through a mail server using [React Email](https://react.email/).
### Middleware
Custom middleware for handling requests and responses in Zap.ts. It integrates plugins in its logic to provide a seamless experience across the application.
### Providers
Context providers for managing global state and dependencies in Zap.ts such as `ThemeProvider` for theming, `ProgressProvider` for progress bar with [BProgress](https://bprogress.vercel.app/), `NuqsAdapter` to integrate [nuqs](https://nuqs.47ng.com/) to manage search params with type safety and `PluginProviders` to inject providers from Zap.ts plugins.
Theme provider for managing light and dark themes in the application with [next-themes](https://github.com/pacocoursey/next-themes).
### Instrumentation
Instrumentation for the Edge runtime environment.
Instrumentation for the Node.js runtime environment.
Shared instrumentation code for both Edge and Node.js environments, following [Next.js instrumentation guidelines](https://nextjs.org/docs/app/guides/instrumentation#importing-runtime-specific-code).
### Zap.ts Specific
Configuration files for Zap.ts.
Type definitions for Zap.ts configuration.
Zap.ts plugin directories such as `auth`, `blog`, and `waitlist`. Each plugin contains its own routes, components, hooks, and other necessary files to provide specific functionality to the application.
# Deployment
URL: /docs/introduction/deployment
Learn how to deploy your Zap.ts application to various platforms including Docker and cloud providers.
***
title: Deployment
description: Learn how to deploy your Zap.ts application to various platforms including Docker and cloud providers.
-------------------------------------------------------------------------------------------------------------------
# Deployment
Zap.ts is built on **Next.js**, which means you can leverage the full ecosystem of **Next.js** deployment options.
To deploy Zap.ts, refer to the [official Next.js deployment guide](https://nextjs.org/docs/app/getting-started/deploying).
It explains how to deploy a **Next.js** app to platforms like [Digital Ocean](https://www.digitalocean.com/), [Docker](https://www.docker.com/), and more.
## Docker
For [Docker](https://www.docker.com/), a `Dockerfile` and `.dockerignore` are already included—you can modify them as needed.
They were created based on the Next.js recommendations from the documentation above.
Make sure to enable the [standalone](https://nextjs.org/docs/app/api-reference/config/next-config-js/output#automatically-copying-traced-files) option in the `next.config.ts` file which creates a folder at `.next/standalone` containing the necessary files to run your app without installing `node_modules`.
# Getting Started
URL: /docs/introduction/getting-started
Learn how to set up and configure your Zap.ts project, including environment variables, quick scripts, and CLI usage.
***
title: Getting Started
description: Learn how to set up and configure your Zap.ts project, including environment variables, quick scripts, and CLI usage.
----------------------------------------------------------------------------------------------------------------------------------
# Getting Started
## Demo (in 5 minutes)
**Note**: This will be added soon.
## Project structure
Before proceeding, ensure that Zap.ts is installed by following the instructions on the [installation](/docs/introduction/installation) page and make sure to read our [best practices](/docs/misc/best-practices) to learn more about Zap.ts' philosophy.
Since Zap.ts is *simply* a **Next.js starter kit**, you own your code; therefore can keep what you like and get rid of things you don't need. To learn more, read the [architecture](/docs/introduction/architecture) page.
### The `src/` Directory
Zap.ts follows a classic **Next.js** app structure with a `src/` directory. Learn more about the decisions and philosophy in the [best practices](/docs/misc/best-practices) guide.
{/* Other src folders */}
{/* Other plugin folders */}
### Folder Structure
* `src/`: Source code for your Next.js app.
* `app/`: Application routes and pages.
* `components/`: Reusable UI components.
* `hooks/`: Custom React hooks.
* `lib/`: Utility functions and libraries.
* `providers/`: Context and theme providers.
* `rpc/`: Remote procedure call definitions.
* `zap/`: Modular plugins for features like analytics, auth, payments, etc.
* `zap.config.ts`: Central configuration for your app (name, plugins, SEO, etc.).
* `next.config.ts`: Next.js configuration.
* `drizzle.config.*.ts`: Database configuration for Drizzle ORM.
* `.env`: Environment variables for connecting to services.
Each folder and file is designed to keep your project organized, scalable, and easy to maintain. You can add, remove, or customize any part to fit your needs. For more details, see the documentation for each plugin and configuration file.
## Environment variables
The `.env` file connects your app to services like the database or email provider. You can remove the ones you don't need.
Update it with your own settings. Below is an example.
```dotenv
BETTER_AUTH_SECRET=your_better_auth_secret
BETTER_AUTH_URL=http://localhost:3000
DATABASE_URL=your_database_url
DATABASE_URL_DEV=postgresql://postgres:password@localhost:5432/zap_dev
GOOGLE_CLIENT_ID=your_google_client_id
GOOGLE_CLIENT_SECRET=your_google_client_secret
POLAR_ACCESS_TOKEN=your_polar_access_token
POLAR_WEBHOOK_SECRET=your_polar_webhook_secret
RESEND_API_KEY=your_resend_api_key
```
If you need to generate a new `.env` file, you can use the following command using the CLI:
```bash
zap generate env
```
Also, don't forget to configure your environment variables in your Zap.ts deployment environment.
The above `.env` file serves as an example. You should only rely on the instance of Zap.ts that was present during its initial installation.
## Configure the app
Your main configuration file is `zap.config.ts`, located in the root of your project. This file controls the core settings for your Zap.ts app and is designed to be clear, modular, and easy to maintain.
Here’s what you can configure:
* **App Information**: Set your app’s name, description, base URL, and contact emails. These values are used throughout your app and for SEO/meta tags.
* **Plugin Management**: Enable or disable built-in plugins like auth, analytics, payments, blog, AI, and more. Each plugin can be toggled on or off to keep your app lean and focused.
* **Security Settings**: Define [Content Security Policy (CSP)](https://developer.mozilla.org/docs/Web/HTTP/CSP) and [Permissions Policy](https://developer.mozilla.org/docs/Web/HTTP/Headers/Permissions-Policy) for your app. This helps you control what resources can be loaded and what browser features are allowed, improving security and privacy.
* **Default Metadata**: Set up [SEO](https://developer.mozilla.org/docs/Glossary/SEO) and [Open Graph](https://ogp.me/) metadata, including title, description, keywords, author, publisher, and social sharing images. These settings help your app look great in search results and when shared on social media.
You can customize any of these settings to fit your needs. The config file is fully typed and documented, so you’ll get autocompletion and validation in your editor.
Each plugin also has its own configuration file (usually `zap.plugin.config.ts`). For details, see the [Plugins Overview](/docs/plugins/overview).
## Quick scripts
Use these commands to run Zap.ts. Pick your favorite package manager:
```bash
npm run dev # Start the dev server with Turbopack
npm run build # Build your app for production
npm run start # Run the production app
npm run lint # Check your code
npm run format # Format your code
npm run db:push # Push schema changes to database (prod)
npm run dev:db:push # Push schema changes to database (dev)
npm run db:migrate # Run database migrations (prod)
npm run dev:db:migrate # Run database migrations (dev)
npm run db:generate # Generate migration files (prod)
npm run dev:db:generate # Generate migration files (dev)
npm run db:studio # Open Drizzle Studio (prod)
npm run dev:db:studio # Open Drizzle Studio (dev)
npm run db:pull # Pull schema from database (prod)
npm run dev:db:pull # Pull schema from database (dev)
npm run dev:mail # Start email development server
npm run zap # Run Zap CLI commands
```
```bash
yarn dev # Start the dev server with Turbopack
yarn build # Build your app for production
yarn start # Run the production app
yarn lint # Check your code with Biome
yarn format # Format your code with Biome
yarn db:push # Push schema changes to database (prod)
yarn dev:db:push # Push schema changes to database (dev)
yarn db:migrate # Run database migrations (prod)
yarn dev:db:migrate # Run database migrations (dev)
yarn db:generate # Generate migration files (prod)
yarn dev:db:generate # Generate migration files (dev)
yarn db:studio # Open Drizzle Studio (prod)
yarn dev:db:studio # Open Drizzle Studio (dev)
yarn db:pull # Pull schema from database (prod)
yarn dev:db:pull # Pull schema from database (dev)
yarn dev:mail # Start email development server
yarn zap # Run Zap CLI commands
```
```bash
pnpm dev # Start the dev server with Turbopack
pnpm build # Build your app for production
pnpm start # Run the production app
pnpm lint # Check your code with Biome
pnpm format # Format your code with Biome
pnpm db:push # Push schema changes to database (prod)
pnpm dev:db:push # Push schema changes to database (dev)
pnpm db:migrate # Run database migrations (prod)
pnpm dev:db:migrate # Run database migrations (dev)
pnpm db:generate # Generate migration files (prod)
pnpm dev:db:generate # Generate migration files (dev)
pnpm db:studio # Open Drizzle Studio (prod)
pnpm dev:db:studio # Open Drizzle Studio (dev)
pnpm db:pull # Pull schema from database (prod)
pnpm dev:db:pull # Pull schema from database (dev)
pnpm dev:mail # Start email development server
pnpm zap # Run Zap CLI commands
```
```bash
bun run dev # Start the dev server with Turbopack
bun run build # Build your app for production
bun run start # Run the production app
bun run lint # Check your code with Biome
bun run format # Format your code with Biome
bun run db:push # Push schema changes to database (prod)
bun run dev:db:push # Push schema changes to database (dev)
bun run db:migrate # Run database migrations (prod)
bun run dev:db:migrate # Run database migrations (dev)
bun run db:generate # Generate migration files (prod)
bun run dev:db:generate # Generate migration files (dev)
bun run db:studio # Open Drizzle Studio (prod)
bun run dev:db:studio # Open Drizzle Studio (dev)
bun run db:pull # Pull schema from database (prod)
bun run dev:db:pull # Pull schema from database (dev)
bun run dev:mail # Start email development server
bun run zap # Run Zap CLI commands
```
### Additional Development Commands
For advanced development and debugging:
```bash
npm run dev:debug # Start dev server with Node.js debugger
npm run dev:scan # Start dev server with React Scan for performance
npm run dev:trace # Start dev server with Turbopack tracing
npm run build:analyze # Build with bundle analyzer
npm run postbuild # Generate sitemap after build
npm run db:check # Check schema for issues (prod)
npm run dev:db:check # Check schema for issues (dev)
npm run db:export # Export schema (prod)
npm run dev:db:export # Export schema (dev)
npm run db:up # Apply pending migrations (prod)
npm run dev:db:up # Apply pending migrations (dev)
```
```bash
yarn dev:debug # Start dev server with Node.js debugger
yarn dev:scan # Start dev server with React Scan for performance
yarn dev:trace # Start dev server with Turbopack tracing
yarn build:analyze # Build with bundle analyzer
yarn postbuild # Generate sitemap after build
yarn db:check # Check schema for issues (prod)
yarn dev:db:check # Check schema for issues (dev)
yarn db:export # Export schema (prod)
yarn dev:db:export # Export schema (dev)
yarn db:up # Apply pending migrations (prod)
yarn dev:db:up # Apply pending migrations (dev)
```
```bash
pnpm dev:debug # Start dev server with Node.js debugger
pnpm dev:scan # Start dev server with React Scan for performance
pnpm dev:trace # Start dev server with Turbopack tracing
pnpm build:analyze # Build with bundle analyzer
pnpm postbuild # Generate sitemap after build
pnpm db:check # Check schema for issues (prod)
pnpm dev:db:check # Check schema for issues (dev)
pnpm db:export # Export schema (prod)
pnpm dev:db:export # Export schema (dev)
pnpm db:up # Apply pending migrations (prod)
pnpm dev:db:up # Apply pending migrations (dev)
```
```bash
bun run dev:debug # Start dev server with Node.js debugger
bun run dev:scan # Start dev server with React Scan for performance
bun run dev:trace # Start dev server with Turbopack tracing
bun run build:analyze # Build with bundle analyzer
bun run postbuild # Generate sitemap after build
bun run db:check # Check schema for issues (prod)
bun run dev:db:check # Check schema for issues (dev)
bun run db:export # Export schema (prod)
bun run dev:db:export # Export schema (dev)
bun run db:up # Apply pending migrations (prod)
bun run dev:db:up # Apply pending migrations (dev)
```
This list of commands may not be exhaustive and can change over time as Zap.ts evolves. Always check your local package.json for the most up-to-date command list.
## Community and support
Join the Zap.ts community to showcase your apps, stay updated with the latest news, get help, and discuss with other developers.
**Connect with us:**
* [**GitHub Discussions**](https://github.com/alexandretrotel/zap.ts/discussions) – Perfect for feature requests, questions, and community discussions.
* [**Discord**](https://discord.gg/24hXMC3eAa) – Real-time chat with the community.
We're excited to see what you build with Zap.ts!
# Installation
URL: /docs/introduction/installation
Learn how to install and set up Zap.ts with a single command.
***
title: Installation
description: Learn how to install and set up Zap.ts with a single command.
--------------------------------------------------------------------------
# Installation
*Setting up **Zap.ts** is now easier than ever!* With just one command, you can have a fully functional Next.js boilerplate ready to go.
## Quick Installation
You can install Zap.ts with a single command:
```bash
npx create-zap-app@latest
```
```bash
yarn create zap-app
```
```bash
pnpm create zap-app
```
```bash
bun create zap-app
```
## What's Included?
Zap.ts comes packed with plugins to accelerate your development:
* **Authentication** - Authentication you *really own* with Better Auth
* **Database** - A type-safe ORM with Drizzle
* **UI Components** - Beautiful components with shadcn/ui
* **Payments** - Subscription handling ready to go
* **Analytics** - Built-in analytics integration
* **Email** - Transactional emails with Resend
* **And much more...**
Everything is in the `zap/` folder, so it is easy to find and change the code and keep the project neat and organised.
## Getting Started
Ready to build something amazing? Start by understanding Zap.ts' structure with the [getting started guide](/docs/introduction/getting-started) or explore the [plugins overview](/docs/plugins/overview) to see what's possible.
This will guide you through setting up your project with the necessary configurations and dependencies.
# What's Zap.ts?
URL: /docs/introduction/motivation
Introduction to Zap.ts - a Next.js boilerplate designed to help you build applications faster using a modern set of tools.
***
title: What's Zap.ts?
description: Introduction to Zap.ts - a Next.js boilerplate designed to help you build applications faster using a modern set of tools.
---------------------------------------------------------------------------------------------------------------------------------------
# What's Zap.ts?
**Zap.ts** – with the ⚡️ symbol – is a **Next.js** boilerplate designed to help you build applications *faster* using a modern set of tools. It also comes with best practices to build *excellent* modern web applications.
It's *fast* to set up and very *easy* to use. It comes with clear documentation and a carefully selected set of tools that make the developer experience (DX) modern and enjoyable.
## Why it exists?
Starting a new web project always means repeating the *same* steps:
* installing tools such as linters
* setting up a database
* adding login features
* creating email systems
* handling payments
* and more...
A ready-made solution saves time and lets the focus stay on making something useful, not on these boring setup tasks, right?
It gives one easy way to do things, a *framework*, improving the developer experience (DX). This means no need to worry about how it all works inside—just use it, it's ***reliable*** and ***simple***.
And, if you want to dive deeper, the code is open for you to explore and modify in an easy way.
## Who is it for?
*Zap.ts is designed for startups and solo developers who move fast and demand simplicity.*
Startups need tools that keep pace with rapid iteration and scaling. Solo developers want solutions that are straightforward, fast to set up, and don't get in the way.
Built with this in mind, Zap.ts acts as a launchpad to turn your idea into a working product faster than ever.
Here's why it's a game-changer for your team:
* **Cost-Effective**: No need to reinvent the wheel or hire specialists because Zap.ts gives you a production-ready stack for free.
* **Future-Proof**: With flexible tools, you can adapt to new requirements or tech trends without a full rewrite.
* **Scalability**: From prototype to scale, the modern libraries ensure your app grows without breaking.
* **Speed to Market**: Pre-configured tools and seamless integrations mean you skip the setup grind and start building your MVP right away.
* **Vendor Lock-In Avoidance**: We prioritize agnostic, open tools that keep your stack flexible so you're never tied to a single provider or ecosystem.
Whether you're a solo founder or a small team, Zap.ts empowers you to ship fast, iterate often, and compete with the big players.
## Credits
Zap.ts wouldn't exist without those *wonderful* tools:
* [AI Vercel SDK](https://sdk.vercel.ai/): A toolkit for streaming text, handling objects, using RAG (Retrieval-Augmented Generation), and more. It lets you switch between providers without depending on a specific SDK.
* [Better Auth](https://better-auth.com/): A simple and flexible way to set up authentication. It works with any framework, avoids vendor lock-in, and connects seamlessly to your database.
* [Drizzle ORM](https://orm.drizzle.team/): An ORM that lets you write database schemas in TypeScript, sync them with your database, and is easy to use.
* [Flags SDK](https://flags-sdk.dev/): A free SDK to use feature flags that works with any provider.
* [nuqs](https://nuqs.vercel.app/): A library for managing URL state in Next.js applications with type safety and automatic serialization.
* [oRPC](https://orpc.unnoq.com/): An alternative to [tRPC](https://trpc.io/) that supports OpenAPI specs, making it easy to build type-safe APIs for frontend and backend.
* [shadcn/ui](https://ui.shadcn.com/): The best way to get ready-to-use UI components that you can customize however you like.
* [Zustand](https://zustand-demo.pmnd.rs/): A lightweight alternative to Redux and React Context. It helps you write less code, do more, and supports local storage persistence out of the box.
* And more...
# Migrate from Next.js
URL: /docs/migration/migrate-from-nextjs
How to migrate your Next.js project to Zap.ts.
***
title: Migrate from Next.js
description: How to migrate your Next.js project to Zap.ts.
-----------------------------------------------------------
# Migrating from Next.js to Zap.ts
Zap.ts builds on top of [Next.js](https://nextjs.org/), providing a starter kit with additional plugins and features for modern web apps.
## Migration Steps
Coming soon...
# Migrate from React
URL: /docs/migration/migrate-from-react
How to migrate your React project to Zap.ts.
***
title: Migrate from React
description: How to migrate your React project to Zap.ts.
---------------------------------------------------------
# Migrating from React to Zap.ts
Zap.ts is built on top of [Next.js](https://nextjs.org/), which itself is a [React](https://www.react.dev/) framework. This means that migrating from a React project to Zap.ts involves adapting your code to fit within the Next.js ecosystem.
## Migration Steps
1. **Convert to Next.js:**
* Move your routes and pages into Next.js's file-based routing system under `src/app/`. Whether you used [TanStack Router](https://tanstack.com/router), [React Router](https://reactrouter.com/), or another routing library, the migration should be straightforward.
* Update your imports and code to use Next.js conventions (e.g., `next/link`, `next/image`).
* Follow the [React to Next.js migration guide](https://nextjs.org/docs/app/guides/migrating/from-create-react-app).
* Follow the [Next.js to Zap.ts migration guide](/docs/migration/migrate-from-nextjs).
2. **Test and Refine:**
* Run `bun install` to install dependencies.
* Test your app and ensure all routes, and features work as expected.
* Refactor and take advantage of Zap.ts' plugin system.
# Migrate from Vite
URL: /docs/migration/migrate-from-vite
How to migrate your Vite project to Zap.ts.
***
title: Migrate from Vite
description: How to migrate your Vite project to Zap.ts.
--------------------------------------------------------
# Migrating from Vite to Zap.ts
Zap.ts is built on top of [Next.js](https://nextjs.org/), so migrating from [Vite](https://vitejs.dev/) involves first adapting your project to Next.js.
## Migration Steps
1. **Convert to Next.js:**
* Move your Vite routes and pages to Next.js's file-based routing in `src/app/`.
* Update your imports and code to use Next.js conventions (e.g., `next/link`, `next/image`).
* Replace Vite-specific config and plugins with Next.js equivalents.
* Follow the [Vite to Next.js migration guide](https://nextjs.org/docs/app/guides/migrating/from-vite).
* Follow the [Next.js to Zap.ts migration guide](/docs/migration/migrate-from-nextjs).
2. **Test and Refine:**
* Run `bun install` to install dependencies.
* Test your app and ensure all routes, plugins, and features work as expected.
* Refactor and take advantage of Zap.ts' plugin system.
# Why Migrate?
URL: /docs/migration/why-migrate
Understand the benefits of migrating to Zap.ts.
***
title: Why Migrate?
description: Understand the benefits of migrating to Zap.ts.
------------------------------------------------------------
# Why Migrate?
Zap.ts offers a modern architecture with:
* Built-in plugin system for features like authentication, analytics, payments, and more
* First-class TypeScript and Bun support
* Opinionated project structure for scalable apps
* Out-of-the-box support for protected/public routes, global error handling, and advanced middleware
Migrating lets you leverage these features and build on a robust foundation for modern web apps.
## Migration Guides
# Best Practices
URL: /docs/misc/best-practices
Learn the recommended practices for organizing your Zap.ts project, from file structure to performance optimization.
***
title: Best Practices
description: Learn the recommended practices for organizing your Zap.ts project, from file structure to performance optimization.
---------------------------------------------------------------------------------------------------------------------------------
# Best Practices
Zap.ts is built to help you create apps *quickly* with a ***clear*** and ***organized*** structure.
This page explains the recommended way to set up your project and why it works well for building modern apps.
## Project Structure
The `src` folder in Zap.ts is organized to keep your code *clean*, *easy to find*, and *ready to grow* (see [getting started](/docs/introduction/getting-started)). Here's what each folder does:
As a best practice, you should follow these conventions when organizing your code:
FolderDescriptionactionsHolds server actions for handling backend tasks.appContains Next.js app router files, such as pages and layouts.componentsStores reusable UI components. common: General components used across the app. ui: Components styled with shadcn/ui, focusing on design consistency.dataKeeps static data, like JSON files, and feature flags to turn features on or off at build time without a database.dbIncludes database-related code, such as schemas.hooksHolds custom React hooks that can be shared across features.libStores shared utilities, like helper functions or API clients.providersContains React context providers for app-wide state.rpcManages code for type-safe API communication.schemasDefines schemas and API validation schemas for type safety.servicesEncapsulates your business logic and domain operations.storesHolds stores for lightweight state management.stylesIncludes global styles.
## Pages vs. Routes
Inside the `app` folder, you'll find some special folders that help you organize your code. These **do not affect your route structure** — they just make things easier to manage:
FolderDescriptionExamplepublicFor public-facing pages and APIs (no auth required)/(public)/index.tsxprotectedFor protected routes (auth required)/api/(protected)/user/update-account/route.ts
These folders let you group your logic by access level without affecting the final URL structure.
In Next.js, routes come in *two main types*:
* **API**: A backend endpoint for handling HTTP requests. Used for data fetching, mutations, etc.
* **Page**: A UI screen rendered by a React component. These can be public or protected, static or dynamic.
Learn more in the [Next.js documentation](https://nextjs.org/docs/app/getting-started/project-structure#routing-files).
## Server Actions vs. API Routes
**Server Actions** and **API Routes** both handle *backend* logic, but they work differently:
* **Server Actions**: Server-side functions for tasks like form submissions. They run on the server and are good for one-off operations. They don't need a separate endpoint.
* **API Routes**: Next.js endpoints (e.g., `/api/users`) for reusable APIs. They're better for parallel requests and external access. With oRPC, they become type-safe.
It's important to note that **API Routes** handle concurrent requests, making them ideal for data fetching and external APIs, while **Server Actions** run sequentially and are better suited for isolated *mutation* tasks.
In general, we advise against using **Server Actions**. They are essentially another way to define **API Routes**, but with less control and flexibility.
## Providers vs. Zustand Stores
The `providers` folder is for React context providers, but we recommend using Zustand stores for state management whenever possible.
**React Context** is great for static or infrequently changing values (like themes or locales), but it can lead to unnecessary re-renders when used for dynamic state.
```tsx
import React, { createContext, useState, useContext, ReactNode } from "react";
type Theme = "light" | "dark";
interface ThemeContextType {
theme: Theme;
setTheme: (theme: Theme) => void;
toggleTheme: () => void;
}
const ThemeContext = createContext(undefined);
export function ThemeProvider({ children }: { children: ReactNode }) {
const [theme, setTheme] = useState("light");
const toggleTheme = () => {
setTheme((prev) => (prev === "light" ? "dark" : "light"));
};
return (
{children}
);
}
export function useTheme() {
const context = useContext(ThemeContext);
if (!context) {
throw new Error("useTheme must be used within a ThemeProvider");
}
return context;
}
```
**Zustand**, on the other hand, is a lightweight state manager that avoids this problem by isolating updates and keeping your components more performant.
```ts
import { create } from "zustand";
export const useCartStore = create(set => ({
items: [],
addItem: item => set(state => ({ items: [...state.items, item] })),
}));
```
We recommend you to check [Zustand documentation](https://zustand.docs.pmnd.rs/getting-started/introduction) to learn more.
Use `providers` only when you have no other choice (e.g., for third-party libraries requiring context). For app state, use Zustand stores in the `stores` folder—they're lighter and easier to manage.
## URL State Management
For state that should be **shareable via URL** (like filters, search terms, or pagination), use [nuqs](https://nuqs.vercel.app/) — a powerful library that makes URL state management as simple as `useState`.
**nuqs** provides hooks that automatically sync your component state with URL search parameters, enabling:
* **Shareable URLs** — Users can bookmark or share filtered views
* **Browser navigation** — Back/forward buttons work naturally with your app state
* **Deep linking** — Direct links to specific app states
* **SEO-friendly URLs** — Search engines can index different states of your app
**nuqs** makes it easy to implement these features with minimal boilerplate. See the below example.
```tsx
"use client";
import { parseAsInteger, useQueryState } from "nuqs";
export function Demo() {
const [hello, setHello] = useQueryState("hello", { defaultValue: "" });
const [count, setCount] = useQueryState(
"count",
parseAsInteger.withDefault(0),
);
return (
<>
setHello(e.target.value || null)}
/>
Hello, {hello || "anonymous visitor"}!
>
);
}
```
## Type-Safe APIs
The `schemas` folder uses **Zod** to define validation schemas for your database and API requests.
These schemas ensure your data always matches the expected shape, reducing bugs and runtime errors.
```ts
// src/schemas/product.schema.ts
import { z } from "zod";
export const ProductSchema = z.object({
id: z.string(),
name: z.string(),
price: z.number(),
});
```
With **oRPC**, you leverage these schemas to enforce **end-to-end type safety**—from frontend to backend—so your types are automatically inferred and consistent across your entire app.
```ts
// src/rpc/procedures/product.rpc.ts
import { os } from "@orpc/server";
import { z } from "zod";
const ProductSchema = z.object({
id: z.string(),
name: z.string(),
price: z.number(),
});
export const getProduct = os
.input(ProductSchema.pick({ id: true }))
.output(ProductSchema)
.handler(async ({ input }) => {
// ...fetch product from database or service
return { id: input.id, name: "Sample", price: 10 };
})
.callable();
```
Moreover, we consider **TypeScript mandatory** because it catches errors early, improves developer productivity, and makes your codebase more maintainable and scalable as it grows.
Contrary to common belief, focusing on type safety and strong typing actually helps you build ***faster*** and with ***more confidence***—by preventing subtle bugs and costly refactors down the line, not to mention enabling **powerful IntelliSense** that speeds up development.
## Arrow Functions vs. Named Functions
Understanding when to use arrow functions versus named functions is crucial for writing clean, maintainable code.
Each has specific use cases where they excel:
### Arrow Functions
* **Event handlers and callbacks** — They automatically bind `this` and are more concise
```tsx
const handleClick = () => {
setCount(prev => prev + 1)
}
```
* **Simple utility functions** — When the function is short and focused
```tsx
const formatCurrency = (amount: number) => `$${amount.toFixed(2)}`
```
* **Array methods** — For map, filter, reduce operations
```tsx
const doubled = numbers.map(n => n * 2)
```
### Named Functions
* **Complex logic** — When the function has multiple responsibilities or is longer
```tsx
function validateUserInput(input: UserInput): ValidationResult {
const errors = []
if (!input.email) {
errors.push('Email is required')
}
if (input.password.length < 8) {
errors.push('Password must be at least 8 characters')
}
return { isValid: errors.length === 0, errors }
}
```
* **Recursive functions** — Named functions can reference themselves
```tsx
function factorial(n: number): number {
return n <= 1 ? 1 : n * factorial(n - 1)
}
```
* **Functions that need hoisting** — When you need to call the function before it's defined
```tsx
function processData() {
return transformData(validateData())
}
function validateData() { /* ... */ }
function transformData() { /* ... */ }
```
* **Class methods** — For object-oriented patterns
```tsx
class UserService {
async getUser(id: string) {
return await this.api.get(`/users/${id}`)
}
}
```
### Explanations
**Hoisting** is a JavaScript mechanism where function and variable declarations are moved to the top of their scope during the compilation phase.
**Named function** declarations are *fully hoisted*, meaning you can call them before they're defined in your code.
```ts
// Named function (hoisted)
console.log(square(5)); // 25
function square(x) {
return x * x;
}
// Arrow function (not hoisted)
// console.log(double(5)); // ReferenceError: Cannot access 'double' before initialization
const double = (x) => x * 2;
```
However, arrow functions are not hoisted because they're assigned to variables using `const` or `let`, which follow the temporal dead zone rule.
Additionally, **React DevTools** displays component names more clearly when using named functions.
```tsx
// Named function component (shows as 'UserCard' in DevTools)
function UserCard({ user }) {
return
{user.name}
;
}
// Arrow function component (shows as 'Anonymous' or less descriptive)
const UserCard = ({ user }) => {
return
{user.name}
;
};
```
Indeed, arrow functions assigned to variables often show up as "Anonymous" or with less descriptive names in the component tree, making debugging more difficult.
Thus, named functions offer superior debugging capabilities and component identification in React DevTools compared to anonymous arrow functions.
## Performance & Optimization
Performance directly impacts user experience and SEO. Here are the key Next.js *optimization strategies* to understand:
* **Bundle Analysis**\
Regularly analyze your bundles with tools like [`@next/bundle-analyzer`](https://www.npmjs.com/package/@next/bundle-analyzer) to find and reduce large dependencies or unnecessary code.
* **Lazy Loading (Dynamic Import)**\
Use [dynamic imports](https://nextjs.org/docs/app/guides/lazy-loading) (`dynamic()`) to load heavy or rarely used components on demand, reducing the initial bundle size and speeding up page loads.
```tsx
// Lazy load a heavy component
import dynamic from "next/dynamic";
const HeavyComponent = dynamic(() => import("@/components/HeavyComponent"), {
loading: () =>
Loading...
,
ssr: false,
});
export default function Page() {
return ;
}
```
* **Route Prefetching**\
Take advantage of Next.js's automatic [link prefetching](https://nextjs.org/docs/app/api-reference/components/link#prefetch) (``) to preload pages users are likely to visit next, enabling faster navigation.
```tsx
import Link from "next/link";
export default function Nav() {
return (
);
}
```
* **SSR vs SSG vs ISR**
* *SSR ([Server-Side Rendering](https://nextjs.org/docs/app/guides/migrating/app-router-migration#server-side-rendering-getserversideprops))*: Best for dynamic pages that need fresh data on every request such as user dashboards.
* *SSG ([Static Site Generation](https://nextjs.org/docs/app/guides/migrating/app-router-migration#static-site-generation-getstaticprops))*: Ideal for mostly static pages that rarely change like marketing pages.
* *ISR ([*Incremental Static Generation*](https://nextjs.org/docs/app/guides/incremental-static-regeneration))*: A hybrid approach for mostly static pages with occasional updates, like blogs with frequent content changes.
```tsx
// SSR: app/dashboard/page.tsx
export default async function Page() {
const res = await fetch("https://api.example.com/user", { cache: "no-store" });
const user = await res.json();
return
{user.name}
;
}
// SSG: app/posts/[id]/page.tsx
export async function generateStaticParams() {
const res = await fetch("https://api.example.com/posts");
const posts = await res.json();
return posts.map((post) => ({ id: post.id }));
}
export default async function Page({ params }) {
const res = await fetch(`https://api.example.com/posts/${params.id}`);
const post = await res.json();
return
{post.title}
{post.body}
;
}
// ISR: app/blog/page.tsx
export const revalidate = 60; // seconds
export default async function Page() {
const res = await fetch("https://api.example.com/blog");
const blog = await res.json();
return
{blog.title}
;
}
```
## Middleware
Next.js **Middleware** lets you intercept HTTP requests before they reach your pages or APIs, use it to:
* Handle authentication and conditional redirects
* Modify HTTP headers for security (CSP, CORS)
* Implement dynamic routing or localization
It leverages the **Edge Runtime** that runs your code at the network edge, *closest to users*, providing *ultra-low latency* and *instant scalability*.
## Naming Files
Name TypeFile NamingExampleComponentcomponent-name.tsxuser-card.tsxConstant (data folder)UPPERCASEFLAGS, BASE\_URLDatabase Schemayour-schema.sql.tsauth.sql.tsHookuse-hook.tsuse-user-profile.tsMailyour-mail.mail.tstemplate.mail.tsxQueryyour-query.query.tsget-users.query.tsRPC Procedureyour-procedure.rpc.tsuser.rpc.tsServer Actionyour-action.action.tsupdate-user.action.tsServiceyour-service.service.tsupdate-user.service.tsStoreyour-store.store.tsuser.store.tsZod Schemayour-schema.schema.ts Prefer PascalCase for schema namesuser.schema.ts UserSchema (not userSchema)
## Maximize Your IDE Efficiency
It may sound *cliché*, but using your IDE's search and navigation features can save you a lot of time when jumping between files.
In VSCode, hold `CMD` (or `Ctrl` on Windows) and left-click a file name (e.g., `use-user-profile.ts`) to open it quickly.
## Rationale
These best practices are designed with *scalability*, *maintainability*, and *developer experience* in mind:
* **Clear separation of concerns** keeps your code modular, making it easier to navigate and update without breaking unrelated parts.
* Using **type-safe APIs** drastically reduces runtime errors and boosts confidence by catching bugs early during development.
* Favoring **Zustand over React context** for app state prevents unnecessary re-renders and improves performance.
* Emphasizing **TypeScript as mandatory** ensures consistent code quality, better refactoring, and superior tooling support (like IntelliSense).
* Leveraging **Next.js's file-system routing** alongside logical folder grouping makes your app structure intuitive without complicating URLs.
* Encouraging **IDE efficiency** habits minimizes friction in your workflow, allowing you to focus more on building features than on hunting down files.
In short, this approach balances *speed*, *robustness*, and *clarity* to help you build modern apps that last.
# How to Contribute
URL: /docs/misc/contributing
Learn how to contribute to Zap.ts
***
title: How to Contribute
description: Learn how to contribute to Zap.ts
----------------------------------------------
# How to Contribute to Zap.ts
Thank you for your interest in contributing to Zap.ts! We welcome all contributions, whether you're fixing bugs, improving documentation, or adding new features.
## Getting Started
1. **Fork the repository**
* Click the "Fork" button on GitHub to create your own copy.
2. **Clone your fork**
* `git clone https://github.com//zap.ts.git`
* `cd zap.ts`
* `git remote add upstream https://github.com/alexandretrotel/zap.ts.git`
3. **Create a new branch**
* `git checkout -b my-feature-branch`
## Setting Up the Monorepo
1. **Install dependencies**
* Run `bun install` from the root directory to install all packages.
2. **Set up environment variables**
* In the `core/` directory, run: `zap generate env`
* Rename the generated file to `.env` inside `core/`.
* Run `bun install` again in `core/`.
The `.env` file may be required for the `core` package to compile and for Husky pre-commit hooks to pass. If Husky blocks your commit, you may use `git commit --no-verify` and/or `git push --no-verify`, but this is discouraged and may reduce the chance of your PR being merged.
## Making Changes
* Make your changes in a dedicated branch.
* Ensure your code passes all checks and tests.
* If you add or change features, create a changeset: `bun changeset`.
## Opening a Pull Request
1. **Push your branch**
* `git push origin my-feature-branch`
2. **Open a PR**
* Go to your fork on GitHub and click "Compare & pull request".
* Fill out the PR template and describe your changes.
## Review Process
* Your PR will be reviewed by maintainers.
* Address any requested changes.
* Once approved, your PR will be merged.
## Quality and DX tools
* **[Husky](https://typicode.github.io/husky/#/)**: Enforces pre-commit checks for code quality.
* **[Ultracite](https://www.ultracite.ai)**: Ensures accessibility and code style rules.
* **[Changesets](https://github.com/changesets/changesets)**: Used for managing versioning and changelogs.
* **[Turbo](https://turbo.build/)**: Used for fast monorepo builds, caching, and running tasks efficiently across packages.
## Additional Resources
If needed, open an issue. You can also join the [GitHub discussions](https://github.com/alexandretrotel/zap.ts/discussions) or the [Discord](https://discord.gg/24hXMC3eAa).
Thanks for helping make Zap.ts better!
# Overview
URL: /docs/plugins/overview
Discover all plugins included in Zap.ts and how they accelerate your development.
***
title: Overview
description: Discover all plugins included in Zap.ts and how they accelerate your development.
----------------------------------------------------------------------------------------------
# Overview
Zap.ts comes with a curated set of plugins to help you build modern web applications faster and with best practices out of the box. Here’s a quick overview of what’s included.
### The `zap/` Directory
Zap.ts gives you additional plugins that follows a modular approach, since each plugin is encapsulated in its own directory under `zap/`.
## Core Plugins
Coming soon...
## Additional Integrations
Coming soon...
## How to Use Plugins
Each plugin is documented with guides and examples. Explore their documentation page for detailed instructions on setup, customization, and best practices.