### Install Dependencies and Start Development Server
Source: https://github.com/rari-build/rari/blob/main/packages/create-rari-app/templates/default/README.md
Installs project dependencies and starts the development server. Ensure you have the necessary package manager (npm, yarn, pnpm) configured.
```bash
# Install dependencies
{{INSTALL_COMMAND}}
# Start development server
{{PACKAGE_MANAGER}} run dev
```
--------------------------------
### Install node-pg-migrate
Source: https://github.com/rari-build/rari/blob/main/web/public/content/docs/getting-started/database.mdx
Install the node-pg-migrate package using your preferred package manager.
```bash
pnpm add node-pg-migrate
```
```bash
npm install node-pg-migrate
```
```bash
yarn add node-pg-migrate
```
```bash
bun add node-pg-migrate
```
--------------------------------
### Install Postgres Client
Source: https://github.com/rari-build/rari/blob/main/web/public/content/docs/getting-started/database.mdx
Install the `postgres` client for Node.js. This is a popular choice for connecting to PostgreSQL databases.
```bash
pnpm add postgres
```
```bash
npm install postgres
```
```bash
yarn add postgres
```
```bash
bun add postgres
```
--------------------------------
### Start Development Server
Source: https://github.com/rari-build/rari/blob/main/web/public/content/docs/getting-started.mdx
Run this command to start the local development server for your rari application. Choose your preferred package manager.
```bash
pnpm dev
```
```bash
npm run dev
```
```bash
yarn dev
```
```bash
bun dev
```
--------------------------------
### Build and Start Rari Application
Source: https://github.com/rari-build/rari/blob/main/web/public/content/docs/getting-started/deploying.mdx
Use these commands to build your Rari application for production and start the server. Ensure the PORT environment variable is set if required.
```bash
npx rari build
```
```bash
PORT=8080 npx rari start
```
--------------------------------
### Self-Hosting Rari Application Dependencies
Source: https://github.com/rari-build/rari/blob/main/web/public/content/docs/getting-started/deploying.mdx
General steps for self-hosting a Rari application on any Node.js platform, starting with installing dependencies.
```bash
# Install dependencies
npm install
```
--------------------------------
### Install Prisma Client and Prisma CLI
Source: https://github.com/rari-build/rari/blob/main/web/public/content/docs/getting-started/database.mdx
Install Prisma Client for database access and the Prisma CLI for database schema migrations and management. This is a popular ORM for Node.js.
```bash
pnpm add @prisma/client && pnpm add -D prisma
```
```bash
npm install @prisma/client && npm install -D prisma
```
```bash
yarn add @prisma/client && yarn add -D prisma
```
```bash
bun add @prisma/client && bun add -D prisma
```
--------------------------------
### Catch-All Segments Example
Source: https://github.com/rari-build/rari/blob/main/web/public/content/docs/getting-started/routing.mdx
Illustrates how to create catch-all routes using `[...param]` to match one or more URL segments. The example shows the file structure and how the 'slug' parameter captures multiple segments.
```bash
src/app/docs/[...slug]/page.tsx
→ /docs/getting-started (slug = ["getting-started"])
→ /docs/api/reference/image (slug = ["api", "reference", "image"])
```
--------------------------------
### Install Drizzle ORM and Kit
Source: https://github.com/rari-build/rari/blob/main/web/public/content/docs/getting-started/database.mdx
Install Drizzle ORM for database interactions and Drizzle Kit for schema management. This setup is suitable for Node.js projects.
```bash
pnpm add drizzle-orm && pnpm add -D drizzle-kit
```
```bash
npm install drizzle-orm && npm install -D drizzle-kit
```
```bash
yarn add drizzle-orm && yarn add -D drizzle-kit
```
```bash
bun add drizzle-orm && bun add -D drizzle-kit
```
--------------------------------
### Install pg Client and Types
Source: https://github.com/rari-build/rari/blob/main/web/public/content/docs/getting-started/database.mdx
Install the `pg` client and its TypeScript types for Node.js. This is a widely used PostgreSQL client library.
```bash
pnpm add pg && pnpm add -D @types/pg
```
```bash
npm install pg && npm install -D @types/pg
```
```bash
yarn add pg && yarn add -D @types/pg
```
```bash
bun add pg && bun add -D @types/pg
```
--------------------------------
### Single Dynamic Segment Example
Source: https://github.com/rari-build/rari/blob/main/web/public/content/docs/getting-started/routing.mdx
Demonstrates how to define routes with a single dynamic segment using square brackets. The example shows the file structure and the corresponding URL paths.
```bash
src/app/blog/[slug]/page.tsx → /blog/hello-world, /blog/my-post
src/app/users/[id]/page.tsx → /users/123, /users/abc
```
--------------------------------
### Fetch URL Parameter Examples
Source: https://github.com/rari-build/rari/blob/main/web/public/content/docs/api-reference/functions/fetch.mdx
Examples of using different types of URLs with the fetch function.
```tsx
// String URL
await fetch('https://api.example.com/posts')
// URL object
await fetch(new URL('/api/posts', 'https://api.example.com'))
// Relative URL (in Route Handlers)
await fetch('/api/data')
```
--------------------------------
### Optional Catch-All Segments Example
Source: https://github.com/rari-build/rari/blob/main/web/public/content/docs/getting-started/routing.mdx
Shows how to define optional catch-all routes using `[[...param]]`, which allows matching the route with or without any segments. The example details the file structure and the resulting 'slug' parameter values.
```bash
src/app/docs/[[...slug]]/page.tsx
→ /docs (slug = undefined)
→ /docs/getting-started (slug = ["getting-started"])
→ /docs/api/reference/image (slug = ["api", "reference", "image"])
```
--------------------------------
### Install Neon Serverless Driver
Source: https://github.com/rari-build/rari/blob/main/web/public/content/docs/getting-started/database.mdx
Install the Neon serverless driver for Node.js. This driver uses HTTP-based connections, which are compatible with Rari.
```bash
pnpm add @neondatabase/serverless
```
```bash
npm install @neondatabase/serverless
```
```bash
yarn add @neondatabase/serverless
```
```bash
bun add @neondatabase/serverless
```
--------------------------------
### Install Kysely
Source: https://github.com/rari-build/rari/blob/main/web/public/content/docs/getting-started/database.mdx
Install Kysely, a type-safe SQL query builder for TypeScript and JavaScript. It's designed for Node.js environments.
```bash
pnpm add kysely
```
```bash
npm install kysely
```
```bash
yarn add kysely
```
```bash
bun add kysely
```
--------------------------------
### Start Production Server Commands
Source: https://github.com/rari-build/rari/blob/main/web/public/content/docs/getting-started.mdx
Commands to run your rari application in production mode after building. Ensures the optimized app is served efficiently.
```bash
pnpm start
```
```bash
npm start
```
```bash
yarn start
```
```bash
bun start
```
--------------------------------
### Create a New Rari App
Source: https://github.com/rari-build/rari/blob/main/README.md
Use npm to create a new Rari application, navigate into the app directory, and start the development server.
```bash
npm create rari-app@latest my-app
cd my-app
npm run dev
```
--------------------------------
### Rari Project Structure Example
Source: https://github.com/rari-build/rari/blob/main/web/public/content/docs/getting-started/routing.mdx
Illustrates the file-based routing conventions and typical organization for a Rari application, including root layout, pages, dynamic routes, and API routes.
```bash
src/app/
├── layout.tsx # Root layout
├── page.tsx # /
├── loading.tsx # Global loading state
├── error.tsx # Global error boundary
├── not-found.tsx # Global 404
├── about/
│ └── page.tsx # /about
├── blog/
│ ├── layout.tsx # Blog layout
│ ├── page.tsx # /blog
│ └── [slug]/
│ ├── page.tsx # /blog/:slug
│ ├── loading.tsx # Loading state for blog posts
│ └── opengraph-image.tsx # Dynamic OG image
├── dashboard/
│ ├── layout.tsx # Dashboard layout (sidebar nav)
│ ├── page.tsx # /dashboard
│ ├── error.tsx # Error boundary for dashboard
│ ├── analytics/
│ │ └── page.tsx # /dashboard/analytics
│ └── settings/
│ └── page.tsx # /dashboard/settings
├── docs/
│ └── [[...slug]]/
│ └── page.tsx # /docs, /docs/*, /docs/*/*
└── api/
└── users/
├── route.ts # GET/POST /api/users
└── [id]/
└── route.ts # GET/PUT/DELETE /api/users/:id
```
--------------------------------
### Server Component Example
Source: https://github.com/rari-build/rari/blob/main/web/public/content/docs/getting-started.mdx
An example of a server component that fetches data asynchronously. Server components run on the server and can utilize async/await and server-only APIs.
```tsx
export default async function ServerComponent() {
const data = await fetch('https://api.example.com/data')
const result = await data.json()
return
{result.message}
}
```
--------------------------------
### Custom Image Loader Example
Source: https://github.com/rari-build/rari/blob/main/web/public/content/docs/api-reference/components/image.mdx
Shows how to use the 'loader' prop with a custom function to generate image URLs, useful for custom CDN configurations.
```tsx
const customLoader = ({ src, width, quality }) => {
return `https://cdn.example.com/${src}?w=${width}&q=${quality}`
}
```
--------------------------------
### Install NPM Packages with Package Managers
Source: https://github.com/rari-build/rari/blob/main/web/public/content/docs/getting-started.mdx
Use your preferred package manager (pnpm, npm, yarn, or bun) to add the 'marked' package to your project.
```bash
pnpm add marked
```
```bash
npm install marked
```
```bash
yarn add marked
```
```bash
bun add marked
```
--------------------------------
### MySQL Database Integration
Source: https://github.com/rari-build/rari/blob/main/web/public/content/docs/getting-started/database.mdx
Connect to and query a MySQL database using the 'mysql2/promise' library. This example demonstrates setting up a connection pool and executing a query.
```typescript
import mysql from 'mysql2/promise'
const pool = mysql.createPool({
host: process.env.DB_HOST,
user: process.env.DB_USER,
password: process.env.DB_PASSWORD,
database: process.env.DB_NAME,
})
export default async function UsersPage() {
const [rows] = await pool.query('SELECT * FROM users')
return
}
```
--------------------------------
### Unoptimized Image Example
Source: https://github.com/rari-build/rari/blob/main/web/public/content/docs/api-reference/components/image.mdx
Demonstrates the 'unoptimized' prop, which serves the image as-is without any optimization. Useful for pre-optimized images or testing.
```tsx
```
--------------------------------
### Image Quality Prop Examples
Source: https://github.com/rari-build/rari/blob/main/web/public/content/docs/api-reference/components/image.mdx
Illustrates the 'quality' prop for image optimization, showing valid and invalid quality values based on the default allowlist.
```tsx
// Valid - 100 is in the default allowlist
// Invalid - 90 is NOT in the default allowlist
// To use quality={90}, add it to your vite.config.ts:
// qualityAllowlist: [25, 50, 75, 90, 100]
```
--------------------------------
### MongoDB Integration
Source: https://github.com/rari-build/rari/blob/main/web/public/content/docs/getting-started/database.mdx
Connect to a MongoDB database using the 'mongodb' driver. This example shows how to create a MongoClient, access a database, and query a collection.
```typescript
import { MongoClient } from 'mongodb'
const client = new MongoClient(process.env.MONGODB_URI!)
const db = client.db('myapp')
export default async function PostsPage() {
const posts = await db.collection('posts').find().toArray()
return
}
```
--------------------------------
### Image Generation with Width and Height Options
Source: https://github.com/rari-build/rari/blob/main/web/public/content/docs/api-reference/components/image-response.mdx
Example of creating an image response with both width and height specified using the ImageResponse constructor.
```tsx
export default function Image() {
return new ImageResponse(
Content
,
{ width: 1200, height: 630 }
)
}
```
--------------------------------
### Start Rari Production Server
Source: https://github.com/rari-build/rari/blob/main/web/public/content/docs/getting-started/deploying.mdx
Launch the production server for your Rari application. It binds to 127.0.0.1:3000 by default, or 0.0.0.0 on supported platforms like Railway and Render.
```bash
rari start
```
--------------------------------
### Image Alt Text Example
Source: https://github.com/rari-build/rari/blob/main/web/public/content/docs/api-reference/components/image.mdx
Illustrates the usage of the 'alt' prop for providing alternative text for accessibility and SEO.
```tsx
```
--------------------------------
### Image Generation with Width Option
Source: https://github.com/rari-build/rari/blob/main/web/public/content/docs/api-reference/components/image-response.mdx
Example of creating an image response with a specified width using the ImageResponse constructor.
```tsx
export default function Image() {
return new ImageResponse(
Content
,
{ width: 1200 }
)
}
```
--------------------------------
### Root Layout Example
Source: https://github.com/rari-build/rari/blob/main/web/public/content/docs/getting-started/routing.mdx
Defines the root layout for the entire application, including navigation and main content area. Persists across all routes.
```tsx
import type { LayoutProps } from 'rari'
export default function RootLayout({ children }: LayoutProps) {
return (
{children}
)
}
```
--------------------------------
### Home Page Component with Server Data Fetching
Source: https://github.com/rari-build/rari/blob/main/web/public/content/docs/getting-started.mdx
Create a home page that fetches data on the server using React Server Components. This example fetches repository stats from the GitHub API.
```tsx
import type { PageProps } from 'rari'
import Counter from '@/components/Counter'
// This is a React Server Component - runs on the server!
export default async function HomePage({ params, searchParams }: PageProps) {
// Fetch data on the server
const response = await fetch('https://api.github.com/repos/facebook/react')
const repoData = await response.json()
return (
Last updated: {new Date(repoData.updated_at).toLocaleDateString()}
{/* Client Component */}
)
}
export const metadata = {
title: 'Home | My rari App',
description: 'Welcome to my rari application',
}
```
--------------------------------
### Static Image Import Example
Source: https://github.com/rari-build/rari/blob/main/web/public/content/docs/api-reference/components/image.mdx
Import images statically using a relative path and pass the imported object to the `src` prop of the Image component. This is useful for local assets.
```tsx
import { Image } from 'rari/image'
import heroImage from './hero.jpg'
export default function HomePage() {
return (
)
}
```
--------------------------------
### Query users using Postgres.js
Source: https://github.com/rari-build/rari/blob/main/web/public/content/docs/getting-started/database.mdx
Fetch user data using the Postgres.js client in a Server Component. This example uses tagged template literals for SQL queries.
```tsx
import { sql } from '@/lib/db'
export default async function UsersPage() {
const users = await sql`
SELECT id, name, email FROM users
ORDER BY created_at DESC
`
return (
Users
{users.map((user) => (
{user.name} ({user.email})
))}
)
}
```
--------------------------------
### Image Gallery Implementation
Source: https://github.com/rari-build/rari/blob/main/web/public/content/docs/api-reference/components/image.mdx
Create an image gallery by mapping over an array of image data and rendering the Image component for each item. This example uses CSS Grid for layout.
```tsx
import { Image } from 'rari/image'
const images = [
{ src: '/gallery-1.jpg', alt: 'Gallery image 1' },
{ src: '/gallery-2.jpg', alt: 'Gallery image 2' },
{ src: '/gallery-3.jpg', alt: 'Gallery image 3' },
]
export default function Gallery() {
return (
{images.map((img, i) => (
))}
)
}
```
--------------------------------
### Fetch with Authentication Header
Source: https://github.com/rari-build/rari/blob/main/web/public/content/docs/api-reference/functions/fetch.mdx
Include an Authorization header with a Bearer token for authenticated requests. This example demonstrates fetching stats with a token from environment variables.
```tsx
export default async function DashboardPage() {
const stats = await fetch('https://api.example.com/stats', {
headers: {
'Authorization': `Bearer ${process.env.API_TOKEN}`,
},
rari: { revalidate: 60 }
}).then(r => r.json())
return (
Dashboard
Active users: {stats.activeUsers}
)
}
```
--------------------------------
### Railway Deployment Configuration (railway.toml)
Source: https://github.com/rari-build/rari/blob/main/web/public/content/docs/getting-started/deploying.mdx
This TOML file configures the build and deploy settings for a Rari application on Railway, including the builder, start command, and health check.
```toml
[build]
builder = "RAILPACK"
[deploy]
startCommand = "npm start"
healthcheckPath = "/_rari/health"
healthcheckTimeout = 300
restartPolicyType = "ON_FAILURE"
restartPolicyMaxRetries = 3
```
--------------------------------
### Render Deployment Configuration (render.yaml)
Source: https://github.com/rari-build/rari/blob/main/web/public/content/docs/getting-started/deploying.mdx
This YAML file defines the service configuration for a Rari application on Render, specifying the web service type, runtime, build, and start commands.
```yaml
services:
- type: web
name: rari-app
runtime: node
plan: free
buildCommand: npm install && npx rari build
startCommand: npm start
healthCheckPath: /_rari/health
envVars:
- key: NODE_ENV
value: production
- key: RUST_LOG
value: info
```
--------------------------------
### Fetch Data in a Server Component Page
Source: https://github.com/rari-build/rari/blob/main/web/public/content/docs/getting-started/routing.mdx
Pages are React Server Components by default, allowing direct data fetching using `async/await`. This example fetches posts from an API.
```tsx
export default async function PostsPage() {
const posts = await fetch('https://api.example.com/posts').then(r => r.json())
return (
{posts.map((post: any) => (
{post.title}
))}
)
}
```
--------------------------------
### Navigate to Project Directory
Source: https://github.com/rari-build/rari/blob/main/web/public/content/docs/getting-started.mdx
Change into the newly created project directory.
```bash
cd my-rari-app
```
--------------------------------
### Deduplicate Identical Fetch Requests
Source: https://github.com/rari-build/rari/blob/main/web/public/content/docs/api-reference/functions/fetch.mdx
Rari automatically deduplicates identical GET requests made during the same render pass. This example shows how duplicate calls to UserProfile with the same userId result in a single network request.
```tsx
async function UserProfile({ userId }: { userId: string }) {
// This fetch is deduplicated if called multiple times
const user = await fetch(`https://api.example.com/users/${userId}`)
.then(r => r.json())
return
{user.name}
}
export default function Page() {
return (
{/* Only one request is made, even though UserProfile is rendered twice */}
)
}
```
--------------------------------
### Active Link Styling with Pathname StartsWith
Source: https://github.com/rari-build/rari/blob/main/web/public/content/docs/getting-started/links.mdx
Provides a method to style links based on whether the current pathname starts with a specific path. This is useful for styling sections or parent links in a navigation hierarchy.
```tsx
const isActiveSection = (path: string) => pathname?.startsWith(path)
Documentation
```
--------------------------------
### Layout with Params and Pathname Props
Source: https://github.com/rari-build/rari/blob/main/web/public/content/docs/getting-started/routing.mdx
Example of a layout that receives and utilizes `params` for dynamic route segments (like user ID) and `pathname` for the current URL path. Useful for context-aware UI.
```tsx
import type { LayoutProps } from 'rari'
export default function UserLayout({ children, params, pathname }: LayoutProps<{ id: string }>) {
return (
Current path: {pathname}
User: {params?.id}
{children}
)
}
```
--------------------------------
### API Route Handler for GET and POST
Source: https://github.com/rari-build/rari/blob/main/web/public/content/docs/getting-started/routing.mdx
Defines `GET` and `POST` handlers for the `/api/users` endpoint. The `GET` handler fetches users, and `POST` creates a new user.
```typescript
import type { RouteHandler } from 'rari'
export const GET: RouteHandler = async (request) => {
const users = await fetchUsers()
return Response.json(users)
}
export const POST: RouteHandler = async (request) => {
const body = await request.json()
const user = await createUser(body)
return Response.json(user, { status: 201 })
}
```
--------------------------------
### API Route Handler for Dynamic Route (GET and DELETE)
Source: https://github.com/rari-build/rari/blob/main/web/public/content/docs/getting-started/routing.mdx
Defines `GET` and `DELETE` handlers for a dynamic API route like `/api/users/:id`. The `GET` handler fetches a specific user, and `DELETE` removes them.
```typescript
import type { RouteHandler } from 'rari'
export const GET: RouteHandler<{ id: string }> = async (request, context) => {
// context is always provided for dynamic routes
const { id } = context!.params
const user = await fetchUser(id)
if (!user) {
return Response.json({ error: 'Not found' }, { status: 404 })
}
return Response.json(user)
}
export const DELETE: RouteHandler<{ id: string }> = async (request, context) => {
const { id } = context!.params
await deleteUser(id)
return new Response(null, { status: 204 })
}
```
--------------------------------
### Configure Postgres.js Client
Source: https://github.com/rari-build/rari/blob/main/web/public/content/docs/getting-started/database.mdx
Initialize the Postgres.js client with connection string and configuration options like SSL, max connections, and timeouts.
```typescript
import postgres from 'postgres'
export const sql = postgres(process.env.DATABASE_URL!, {
ssl: 'require',
max: 10,
idle_timeout: 20,
connect_timeout: 10,
})
```
--------------------------------
### Configure Railway Deployment
Source: https://github.com/rari-build/rari/blob/main/packages/create-rari-app/templates/default/README.md
Sets up the necessary configuration files for deploying the application to Railway. Follow the on-screen instructions after running this command.
```bash
# Configure Railway deployment files
{{PACKAGE_MANAGER}} run deploy:railway
# Follow the instructions to deploy
```
--------------------------------
### Typical rari Project Structure
Source: https://github.com/rari-build/rari/blob/main/web/public/content/docs/getting-started.mdx
An overview of the default directory and file structure for a rari project created with `create-rari-app`. Helps in understanding where to place different types of files.
```bash
my-rari-app/
├── src/
│ ├── app/
│ │ ├── layout.tsx
│ │ ├── page.tsx
│ │ ├── globals.css
│ │ ├── about/
│ │ │ └── page.tsx
│ │ ├── blog/
│ │ │ ├── page.tsx
│ │ │ └── [slug]/
│ │ │ └── page.tsx
│ │ └── users/
│ │ └── [id]/
│ │ └── page.tsx
│ ├── components/
│ │ └── Counter.tsx
│ └── actions/
│ └── todo-actions.ts
├── public/
├── index.html
├── package.json
├── vite.config.ts
├── tsconfig.json
└── .gitignore
```
--------------------------------
### GET /api/users
Source: https://github.com/rari-build/rari/blob/main/web/public/content/docs/getting-started/routing.mdx
Fetches a list of all users. This endpoint is defined in `src/app/api/users/route.ts`.
```APIDOC
## GET /api/users
### Description
Fetches a list of all users.
### Method
GET
### Endpoint
/api/users
### Response
#### Success Response (200)
- users (array) - A list of user objects.
### Response Example
```json
[
{
"id": "1",
"name": "John Doe"
}
]
```
```
--------------------------------
### Basic Fetch Usage in Server Component
Source: https://github.com/rari-build/rari/blob/main/web/public/content/docs/api-reference/functions/fetch.mdx
Demonstrates fetching a list of posts and rendering them in a Server Component.
```tsx
export default async function PostsPage() {
const response = await fetch('https://api.example.com/posts')
const posts = await response.json()
return (
{posts.map((post: any) => (
{post.title}
))}
)
}
```
--------------------------------
### Request Deduplication
Source: https://github.com/rari-build/rari/blob/main/web/public/content/docs/api-reference/functions/fetch.mdx
Identical `GET` requests made during the same render pass are automatically deduplicated.
```APIDOC
## Request Deduplication
### Description
Identical `GET` requests made during the same render pass are automatically deduplicated. If multiple components request the same URL with the same options, only one network request is made.
Deduplication only applies to `GET` requests with identical URLs and options during the same render.
### Example
```tsx
async function UserProfile({ userId }: { userId: string }) {
// This fetch is deduplicated if called multiple times
const user = await fetch(`https://api.example.com/users/${userId}`)
.then(r => r.json())
return
{user.name}
}
export default function Page() {
return (
{/* Only one request is made, even though UserProfile is rendered twice */}
)
}
```
```
--------------------------------
### GET /api/users/[id]
Source: https://github.com/rari-build/rari/blob/main/web/public/content/docs/getting-started/routing.mdx
Fetches a specific user by their ID. This endpoint is defined in `src/app/api/users/[id]/route.ts`.
```APIDOC
## GET /api/users/[id]
### Description
Fetches a specific user by their ID.
### Method
GET
### Endpoint
/api/users/:id
### Parameters
#### Path Parameters
- **id** (string) - Required - The ID of the user to fetch.
### Response
#### Success Response (200)
- **user** (object) - The user object.
#### Error Response (404)
- **error** (string) - "Not found"
### Response Example
```json
{
"id": "1",
"name": "John Doe"
}
```
```
--------------------------------
### Create and Apply Prisma Migrations
Source: https://github.com/rari-build/rari/blob/main/web/public/content/docs/getting-started/database.mdx
Commands for managing database migrations with Prisma. Use 'migrate dev' for development to create migrations and apply them, and 'migrate deploy' for production environments to apply existing migrations.
```bash
# Create migration
npx prisma migrate dev --name init
# Apply migrations in production
npx prisma migrate deploy
```
--------------------------------
### Default Fetch Caching
Source: https://github.com/rari-build/rari/blob/main/web/public/content/docs/api-reference/functions/fetch.mdx
Demonstrates the default caching behavior where GET requests are automatically cached. 'force-cache' is the default option.
```tsx
// These are equivalent
await fetch('https://api.example.com/posts')
await fetch('https://api.example.com/posts', { cache: 'force-cache' })
```
--------------------------------
### Configure Render Deployment
Source: https://github.com/rari-build/rari/blob/main/packages/create-rari-app/templates/default/README.md
Sets up the necessary configuration files for deploying the application to Render. Render automatically detects Node.js and uses the render.yaml file.
```bash
# Configure Render deployment files
{{PACKAGE_MANAGER}} run deploy:render
# Follow the instructions to deploy
```
--------------------------------
### Directory Structure for Nested Layouts
Source: https://github.com/rari-build/rari/blob/main/web/public/content/docs/getting-started/routing.mdx
Illustrates a typical directory structure showing how layouts are organized in subdirectories to wrap specific sections of the application.
```bash
src/app/
├── layout.tsx # Root layout (wraps everything)
├── page.tsx # /
└── dashboard/
├── layout.tsx # Dashboard layout (wraps dashboard pages)
├── page.tsx # /dashboard
├── analytics/
│ └── page.tsx # /dashboard/analytics
└── settings/
└── page.tsx # /dashboard/settings
```
--------------------------------
### Add rari to Existing Vite Project
Source: https://github.com/rari-build/rari/blob/main/web/public/content/docs/getting-started.mdx
Install the rari package as a dependency in your existing Vite project. Choose your preferred package manager.
```bash
pnpm add rari
```
```bash
npm install rari
```
```bash
yarn add rari
```
```bash
bun add rari
```
--------------------------------
### Build Rari Application
Source: https://github.com/rari-build/rari/blob/main/web/public/content/docs/getting-started/deploying.mdx
Run this command to create a production build of your Rari application. It cleans previous output, type checks, bundles with Vite, and pre-optimizes images.
```bash
rari build
```
--------------------------------
### Run Database Migrations
Source: https://github.com/rari-build/rari/blob/main/web/public/content/docs/getting-started/database.mdx
Execute database migrations using the node-pg-migrate CLI.
```bash
npx node-pg-migrate up
```
--------------------------------
### Define an About Page Route
Source: https://github.com/rari-build/rari/blob/main/web/public/content/docs/getting-started/routing.mdx
Create a `page.tsx` file within a subdirectory of `src/app/` to define a nested route. This example creates the `/about` route.
```tsx
export default function AboutPage() {
return
About
}
```
--------------------------------
### Use Appropriate Loading Strategy for Images
Source: https://github.com/rari-build/rari/blob/main/web/public/content/docs/api-reference/components/image.mdx
Employ `loading="eager"` for above-the-fold images that need to be visible immediately. Use the default `loading="lazy"` for below-the-fold images to defer loading until they are in the viewport.
```tsx
// Hero image - load immediately
// Gallery images - lazy load
```
--------------------------------
### Commit and Push to GitHub
Source: https://github.com/rari-build/rari/blob/main/packages/create-rari-app/templates/default/README.md
Stages all changes, creates an initial commit, and pushes to the main branch of your GitHub repository. This is a prerequisite for cloud deployment.
```bash
git add .
git commit -m "Initial commit"
git push origin main
```
--------------------------------
### Create New rari Project
Source: https://github.com/rari-build/rari/blob/main/web/public/content/docs/getting-started.mdx
Use this command to generate a new rari application. Choose your preferred package manager.
```bash
pnpm create rari-app@latest my-rari-app
```
```bash
npm create rari-app@latest my-rari-app
```
```bash
yarn create rari-app my-rari-app
```
```bash
bun create rari-app my-rari-app
```
--------------------------------
### Hash Links for In-Page Navigation
Source: https://github.com/rari-build/rari/blob/main/web/public/content/docs/getting-started/links.mdx
Use anchor tags with 'href' starting with '#'. The router intercepts these to provide smooth scrolling to the element with the matching ID.
```tsx
Jump to Features
Features
```
--------------------------------
### Configuring Image Size via Export
Source: https://github.com/rari-build/rari/blob/main/web/public/content/docs/api-reference/components/image-response.mdx
Demonstrates configuring image dimensions by exporting a 'size' object, an alternative to passing options to the constructor.
```tsx
import { ImageResponse } from 'rari/og'
export const size = {
width: 1200,
height: 630,
}
export default function Image() {
return new ImageResponse(
Content
)
}
```
--------------------------------
### Set Database Connection URL
Source: https://github.com/rari-build/rari/blob/main/web/public/content/docs/getting-started/database.mdx
Add your Neon database connection string to the .env file. Ensure the DATABASE_URL is correctly formatted for your PostgreSQL database.
```bash
DATABASE_URL="postgresql://user:password@ep-cool-darkness-123456.us-east-2.aws.neon.tech/dbname?sslmode=require"
```
--------------------------------
### Image Source: URL vs. Static Import
Source: https://github.com/rari-build/rari/blob/main/web/public/content/docs/api-reference/components/image.mdx
Shows how to use the 'src' prop with either a URL string or a static image import.
```tsx
// URL string
// Static import
import heroImage from './hero.jpg'
```
--------------------------------
### Dashboard Nested Layout Example
Source: https://github.com/rari-build/rari/blob/main/web/public/content/docs/getting-started/routing.mdx
A nested layout for the dashboard section, providing a sidebar navigation and a main content area. It wraps pages within the `/dashboard` route.
```tsx
import type { LayoutProps } from 'rari'
export default function DashboardLayout({ children }: LayoutProps) {
return (
{children}
)
}
```
--------------------------------
### API Route Directory Structure
Source: https://github.com/rari-build/rari/blob/main/web/public/content/docs/getting-started/routing.mdx
Shows the directory structure for creating API endpoints, including dynamic routes.
```bash
src/app/api/
└── users/
├── route.ts # /api/users
└── [id]/
└── route.ts # /api/users/:id
```
--------------------------------
### Generate Render Deployment Configuration
Source: https://github.com/rari-build/rari/blob/main/web/public/content/docs/getting-started/deploying.mdx
Run this command to generate the render.yaml configuration file for deploying your Rari application to Render.
```bash
rari deploy render
```
--------------------------------
### Measure Homepage Performance with curl
Source: https://github.com/rari-build/rari/blob/main/web/public/content/blog/building-rari-with-rari.mdx
Use this bash command to measure the total time and downloaded size of the rari.build homepage, including various compression encodings.
```bash
# Homepage
curl -H "Accept-Encoding: zstd, br, gzip" -w "\nTime: %{time_total}s\nSize: %{size_download} bytes\n" -o /dev/null https://rari.build
```
--------------------------------
### Dockerfile for Rari Containerized Deployment
Source: https://github.com/rari-build/rari/blob/main/web/public/content/docs/getting-started/deploying.mdx
A minimal Dockerfile to containerize your Rari application. It installs necessary dependencies, copies application files, builds the project, and sets up runtime environment variables.
```dockerfile
FROM node:22.12-slim
RUN apt-get update && apt-get install -y libfontconfig1 && rm -rf /var/lib/apt/lists/*
WORKDIR /app
COPY package.json package-lock.json ./
RUN npm ci
COPY . .
RUN npx rari build
ENV NODE_ENV=production
ENV PORT=3000
EXPOSE 3000
CMD ["npm", "start"]
```
--------------------------------
### Image Component Usage
Source: https://github.com/rari-build/rari/blob/main/web/public/content/docs/api-reference/components/image.mdx
Demonstrates the basic usage of the Image component by providing the source, alt text, and dimensions.
```APIDOC
## Image Component
### Description
The `Image` component is used to display images. It supports various props for optimization, layout, and accessibility.
### Props
#### Required Props
- **src** (string | StaticImageData) - Required - The image source. Can be a URL string or a static image import.
- **alt** (string) - Required - Alternative text for the image. Important for accessibility and SEO.
#### Size Props
- **width** (number) - Optional - The intrinsic width of the image in pixels. Required unless using `fill` prop.
- **height** (number) - Optional - The intrinsic height of the image in pixels. Required unless using `fill` prop.
- **fill** (boolean) - Optional - Makes the image fill its parent container. The parent must have `position: relative`, `position: fixed`, or `position: absolute`.
- **sizes** (string) - Optional - Defines which image size to load at different viewport widths. Uses standard responsive image syntax.
#### Optimization Props
- **quality** (number) - Optional - The quality of the optimized image, between 1 and 100. Higher values mean better quality but larger file sizes. Must be in the `qualityAllowlist` configured in `vite.config.ts`.
- **unoptimized** (boolean) - Optional - When true, the image will be served as-is without optimization.
- **loader** ((props: { src: string, width: number, quality: number }) => string) - Optional - Custom function to generate image URLs. Useful for custom CDN configurations.
```
--------------------------------
### Static Data Fetching with fetch
Source: https://github.com/rari-build/rari/blob/main/web/public/content/docs/api-reference/functions/fetch.mdx
Fetch data at build time and cache it. This is the default behavior.
```tsx
export default async function PostsPage() {
const posts = await fetch('https://api.example.com/posts', {
cache: 'force-cache' // Default - cached until revalidation/eviction
}).then(r => r.json())
return (
{posts.map((post: any) => (
{post.title}
))}
)
}
```
--------------------------------
### Fetch with Combined Options
Source: https://github.com/rari-build/rari/blob/main/web/public/content/docs/api-reference/functions/fetch.mdx
Use multiple rari options like revalidate and timeout together in a single fetch request. This example fetches posts with a 5-minute cache and an 8-second timeout.
```tsx
export default async function PostsPage() {
const posts = await fetch('https://api.example.com/posts', {
headers: {
'Authorization': `Bearer ${process.env.API_TOKEN}`,
},
rari: {
revalidate: 300, // Cache for 5 minutes
timeout: 8000 // 8 second timeout
}
}).then(r => r.json())
return (
{posts.map((post: any) => (
{post.title}
))}
)
}
```
--------------------------------
### Client Component Example
Source: https://github.com/rari-build/rari/blob/main/web/public/content/docs/getting-started.mdx
A client component that uses React's useState hook to manage local state. Client components run in the browser and can use hooks and event handlers.
```tsx
'use client'
import { useState } from 'react'
export default function ClientComponent() {
const [count, setCount] = useState(0)
return (
)
}
```
--------------------------------
### Responsive Image with Sizes Prop
Source: https://github.com/rari-build/rari/blob/main/web/public/content/docs/api-reference/components/image.mdx
Shows how to use the 'sizes' prop to define which image size to load at different viewport widths for responsive images.
```tsx
```
--------------------------------
### Layout State Preservation During Navigation
Source: https://github.com/rari-build/rari/blob/main/web/public/content/docs/getting-started/links.mdx
Layout components remain mounted during client-side navigation, preserving their state. This example shows a sidebar whose state persists when navigating between dashboard pages.
```tsx
import { useState } from 'react'
import type { LayoutProps } from 'rari'
export default function DashboardLayout({ children }: LayoutProps) {
const [sidebarOpen, setSidebarOpen] = useState(true)
return (
{children}
)
}
```
--------------------------------
### Basic Image Usage
Source: https://github.com/rari-build/rari/blob/main/web/public/content/docs/api-reference/components/image.mdx
Demonstrates the fundamental usage of the Image component with src, alt, width, and height props.
```tsx
import { Image } from 'rari/image'
export default function HomePage() {
return (
)
}
```
--------------------------------
### Basic ImageResponse Usage
Source: https://github.com/rari-build/rari/blob/main/web/public/content/docs/api-reference/components/image-response.mdx
Create an ImageResponse instance within an opengraph-image.tsx file to generate a dynamic Open Graph image. This example uses JSX and inline styles to define the image content.
```tsx
import { ImageResponse } from 'rari/og'
export default function Image() {
return new ImageResponse(
Welcome to My Site
,
)
}
```
--------------------------------
### Export Configuration: size
Source: https://github.com/rari-build/rari/blob/main/web/public/content/docs/api-reference/components/image-response.mdx
Configure image dimensions by exporting a `size` object, which is an alternative to passing options to the constructor.
```APIDOC
## Export Configuration: size
### Description
Export a `size` object to configure the image dimensions. This is an alternative to passing options to the constructor.
### Example Usage
```tsx
import { ImageResponse } from 'rari/og'
export const size = {
width: 1200,
height: 630,
}
export default function Image() {
return new ImageResponse(
Content
)
}
```
```
--------------------------------
### API Routes for Database Operations
Source: https://github.com/rari-build/rari/blob/main/web/public/content/docs/getting-started/database.mdx
This snippet demonstrates how to use API routes to fetch and create posts in a database using neon. It includes error handling and input validation.
```typescript
import { neon } from '@neondatabase/serverless'
import { ApiResponse } from 'rari'
const sql = neon(process.env.DATABASE_URL!)
// Example: Get current user from session/auth
async function getCurrentUserId() {
// Replace with your actual auth implementation
// e.g., from cookies, session, or auth library
return 1 // Placeholder
}
export async function GET(request: Request) {
try {
const url = new URL(request.url)
const parsedLimit = Number(url.searchParams.get('limit'))
const limit =
Number.isFinite(parsedLimit) && parsedLimit > 0
? Math.min(parsedLimit, 100)
: 10
const posts = await sql`
SELECT id, title, content, created_at
FROM posts
ORDER BY created_at DESC
LIMIT ${limit}
`
return ApiResponse.json({ posts })
} catch (error) {
console.error('Database error - failed to fetch posts')
return ApiResponse.json(
{ error: 'Failed to fetch posts' },
{ status: 500 }
)
}
}
export async function POST(request: Request) {
try {
const userId = await getCurrentUserId()
if (!userId) {
return ApiResponse.json(
{ error: 'Unauthorized' },
{ status: 401 }
)
}
const { title, content } = await request.json()
if (!title || !content) {
return ApiResponse.json(
{ error: 'Title and content are required' },
{ status: 400 }
)
}
const result = await sql`
INSERT INTO posts (title, content, user_id)
VALUES (${title}, ${content}, ${userId})
RETURNING id, title, content, created_at
`
return ApiResponse.json({ post: result[0] }, { status: 201 })
} catch (error) {
console.error('Database error - failed to create post')
return ApiResponse.json(
{ error: 'Failed to create post' },
{ status: 500 }
)
}
}
```
--------------------------------
### Query posts using Drizzle ORM
Source: https://github.com/rari-build/rari/blob/main/web/public/content/docs/getting-started/database.mdx
Fetch recent posts using Drizzle ORM in a Server Component. This example demonstrates selecting, ordering, and limiting results based on the defined schema.
```tsx
import { db } from '@/lib/db'
import { posts } from '@/lib/schema'
import { desc } from 'drizzle-orm'
export default async function PostsPage() {
const allPosts = await db
.select()
.from(posts)
.orderBy(desc(posts.createdAt))
.limit(10)
return (
Recent Posts
{allPosts.map((post) => (
{post.title}
{post.content}
))}
)
}
```
--------------------------------
### Prefetch Routes Programmatically with useRouter
Source: https://github.com/rari-build/rari/blob/main/web/public/content/docs/getting-started/links.mdx
Use the `useRouter` hook to prefetch routes when a user hovers over a link. This improves perceived performance by loading route data in advance.
```tsx
'use client'
import { useRouter } from 'rari/router'
export default function ProductCard({ href }: { href: string }) {
const router = useRouter()
return (
)
}
```
--------------------------------
### Configure node-postgres (pg) Pool
Source: https://github.com/rari-build/rari/blob/main/web/public/content/docs/getting-started/database.mdx
Set up a connection pool for node-postgres (pg). Configure SSL based on the DATABASE_ALLOW_INSECURE_SSL environment variable.
```typescript
import { Pool } from 'pg'
export const pool = new Pool({
connectionString: process.env.DATABASE_URL,
ssl: process.env.DATABASE_ALLOW_INSECURE_SSL === 'true'
? { rejectUnauthorized: false }
: true,
max: 20,
idleTimeoutMillis: 30000,
connectionTimeoutMillis: 2000,
})
```
--------------------------------
### Generate Blog Post Card Image
Source: https://github.com/rari-build/rari/blob/main/web/public/content/docs/api-reference/components/image-response.mdx
Generates an image for a blog post card, fetching post data dynamically. This example shows how to integrate data fetching and apply more complex styling, including borders and background colors, to display a post title and excerpt.
```tsx
import type { PageProps } from 'rari'
import { ImageResponse } from 'rari/og'
export const size = { width: 1200, height: 630 }
export default async function Image({ params }: PageProps<{ slug: string }>) {
const post = await fetch(`https://api.example.com/posts/${params.slug}`)
.then(res => res.json())
return new ImageResponse(