### Quick Start Commands
Source: https://github.com/craxjs/crax/blob/main/packages/create-crax-app/template/README.md
Commands to install dependencies and start the development server.
```bash
npm install
npm run dev
```
--------------------------------
### Start the development server
Source: https://github.com/craxjs/crax/blob/main/packages/docs-site/docs/guide/start/getting-started.mdx
Navigate into the project directory, install dependencies, and launch the development server.
```bash
cd my-app
pnpm install
pnpm dev
```
--------------------------------
### Run Pokedex Example
Source: https://github.com/craxjs/crax/blob/main/packages/docs-site/docs/guide/examples/pokedex.mdx
Commands to clone and start the Pokedex example project locally.
```bash
git clone https://github.com/craxjs/crax.git
cd crax/packages/example
npm install
npm run dev
```
--------------------------------
### Install dependencies
Source: https://github.com/craxjs/crax/blob/main/packages/docs-site/README.md
Run this command to install the necessary project dependencies.
```bash
pnpm install
```
--------------------------------
### Start development server
Source: https://github.com/craxjs/crax/blob/main/packages/docs-site/docs/guide/features/cli-commands.mdx
Launches the Vite development server with Hot Module Replacement.
```bash
pnpm dev
```
--------------------------------
### Complete SEO implementation
Source: https://github.com/craxjs/crax/blob/main/packages/docs-site/docs/guide/features/seo.mdx
A full example demonstrating how to integrate multiple SEO tags within a page component.
```tsx
import { Head } from '@crax/seo'
export default function DashboardPage() {
return (
<>
Dashboard | Crax{/* page content */}
>
)
}
```
--------------------------------
### Install vite-ssg dependency
Source: https://github.com/craxjs/crax/blob/main/packages/docs-site/docs/guide/features/ssg.mdx
Add the vite-ssg plugin to your project as a development dependency.
```bash
pnpm add -D vite-ssg
```
--------------------------------
### Integrate vite-plugin-pwa
Source: https://github.com/craxjs/crax/blob/main/packages/docs-site/docs/guide/features/pwa.mdx
Install and configure the Vite PWA plugin for offline support and service worker management.
```bash
pnpm add -D vite-plugin-pwa
```
```ts
// vite.config.ts
import { VitePWA } from 'vite-plugin-pwa'
export default defineConfig({
plugins: [
VitePWA({
registerType: 'autoUpdate',
includeAssets: ['pwa/*.png'],
manifest: false, // handled by crax
}),
],
})
```
--------------------------------
### Generate VAPID Keys for Push Notifications
Source: https://github.com/craxjs/crax/blob/main/packages/docs-site/docs/guide/features/pwa.mdx
Commands to install web-push and generate the necessary VAPID keys for push notification security.
```bash
pnpm add -D web-push
npx web-push generate-vapid-keys
```
```bash
VITE_VAPID_PUBLIC_KEY=your-public-key
VAPID_PRIVATE_KEY=your-private-key
VAPID_SUBJECT=mailto:you@example.com
```
--------------------------------
### Server-Side Push Notification Sending
Source: https://github.com/craxjs/crax/blob/main/packages/docs-site/docs/guide/features/pwa.mdx
Install web-push and use it on the server to send notifications to subscribed clients.
```bash
pnpm add web-push
```
```ts
import webpush from "web-push"
webpush.setVapidDetails(
process.env.VAPID_SUBJECT!,
process.env.VITE_VAPID_PUBLIC_KEY!,
process.env.VAPID_PRIVATE_KEY!
)
// Send notification
await webpush.sendNotification(subscription, JSON.stringify({
title: "Hello!",
body: "This is a push notification",
}))
```
--------------------------------
### Enforcing layout dimensions
Source: https://github.com/craxjs/crax/blob/main/packages/docs-site/docs/guide/features/image-optimization.mdx
Examples showing how width and height requirements prevent layout shifts, and the fullWidth layout escape hatch.
```tsx
// ❌ Type error: width/height (or aspectRatio) missing
// ✅ compiles — fixed intrinsic size, "constrained" layout (default)
// ✅ compiles — the escape hatch. Stretches to fill the container; height is
// optional here since the container determines the rendered size.
```
--------------------------------
### Auto-Injected HTML Tags
Source: https://github.com/craxjs/crax/blob/main/packages/docs-site/docs/guide/features/pwa.mdx
Example of the HTML tags automatically injected into index.html when PWA is enabled.
```html
```
--------------------------------
### Build the application
Source: https://github.com/craxjs/crax/blob/main/packages/create-crax-app/template/skills/crax/SKILL.md
Compiles the project into the dist directory for static hosting.
```bash
pnpm build
```
--------------------------------
### Preview production build
Source: https://github.com/craxjs/crax/blob/main/packages/docs-site/docs/guide/features/cli-commands.mdx
Serves the production build locally to verify the output.
```bash
pnpm preview
```
--------------------------------
### Initialize root application component
Source: https://github.com/craxjs/crax/blob/main/templates/v1/skills/crax/SKILL.md
Set up the QueryClientProvider and CraxRouter in the main application entry point.
```tsx
// src/App.tsx
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
import { ReactQueryDevtools } from '@tanstack/react-query-devtools'
import { CraxRouter } from '@crax/router'
const queryClient = new QueryClient({
defaultOptions: {
queries: {
staleTime: 1000 * 60,
retry: 1,
},
},
})
export function App() {
return (
)
}
```
--------------------------------
### Deploy via Docker or static hosting
Source: https://github.com/craxjs/crax/blob/main/packages/docs-site/docs/guide/skill.mdx
Commands for building and running the application in a Docker container or deploying static files.
```bash
# Docker
docker build -t my-app .
docker run -p 3000:80 my-app
# Static hosting (Vercel, Netlify, Cloudflare Pages)
# Just point to dist/ directory
```
--------------------------------
### Scaffold a new project
Source: https://github.com/craxjs/crax/blob/main/packages/docs-site/docs/guide/features/cli-commands.mdx
Initializes a new project using the Crax starter template via various package managers.
```bash
# npm
npx @craxjs/crax create my-app
# pnpm
pnpm dlx @craxjs/crax create my-app
# yarn
yarn dlx @craxjs/crax create my-app
```
--------------------------------
### createStore
Source: https://github.com/craxjs/crax/blob/main/templates/v1/skills/crax/SKILL.md
Creates a new store instance with an initial value and optional configuration.
```APIDOC
## createStore(initialValue, config?)
### Description
Initializes a new store. Supports primitives, objects, and optional configuration for features like history tracking.
### Parameters
- **initialValue** (any) - Required - The initial state of the store.
- **config** (object) - Optional - Configuration object (e.g., { maxHistorySize: number }).
### Example
```typescript
import { createStore } from '@crax/store';
const store = createStore(0, { maxHistorySize: 20 });
```
```
--------------------------------
### Build and Run Docker Container
Source: https://github.com/craxjs/crax/blob/main/packages/docs-site/docs/guide/features/deploy.mdx
Commands to build the Docker image and run the container locally.
```bash
docker build -t my-app .
docker run -p 8080:80 my-app
```
--------------------------------
### Build for Production
Source: https://github.com/craxjs/crax/blob/main/packages/docs-site/docs/guide/features/deploy.mdx
Generates the static assets required for deployment in the dist/ directory.
```bash
pnpm build
```
--------------------------------
### Scaffold a new CRAX project
Source: https://github.com/craxjs/crax/blob/main/packages/docs-site/docs/guide/start/introduction.mdx
Use the npx command to initialize a new project with the CRAX framework.
```bash
npx @craxjs/crax create my-app
```
--------------------------------
### Define stores in small projects
Source: https://github.com/craxjs/crax/blob/main/packages/docs-site/docs/guide/skill.mdx
Initialize multiple stores in a single file using createStore.
```tsx
import { createStore } from '@crax/store'
export const themeStore = createStore<'light' | 'dark'>('light')
export const authStore = createStore({ user: null, isLoggedIn: false })
export const cartStore = createStore<{ id: number; qty: number }[]>([])
```
--------------------------------
### createStore(initialValue: T)
Source: https://github.com/craxjs/crax/blob/main/packages/docs-site/docs/guide/features/state-management.mdx
Initializes a new global store with a given initial value.
```APIDOC
## createStore(initialValue: T)
### Description
Creates a new store instance that holds state in memory. The store persists across client-side navigation.
### Parameters
- **initialValue** (T) - Required - The initial state value for the store.
### Example
```typescript
import { createStore } from '@crax/store';
export const themeStore = createStore<'light' | 'dark'>('light');
```
```
--------------------------------
### Initialize stores with createStore
Source: https://github.com/craxjs/crax/blob/main/templates/v1/skills/crax/SKILL.md
Create primitive, object, or history-tracked stores using the createStore factory.
```tsx
import { createStore } from '@crax/store'
// Primitive store
const themeStore = createStore<'light' | 'dark'>('light')
// Object store
const userStore = createStore({
name: '',
email: '',
isLoggedIn: false,
})
// With config (history tracking)
const counterStore = createStore(0, { maxHistorySize: 20 })
```
--------------------------------
### Store Instance API
Source: https://github.com/craxjs/crax/blob/main/templates/v1/skills/crax/SKILL.md
Methods and properties available on a store instance.
```APIDOC
## Store Instance Methods
### Properties
- **value** (any) - Get or set the current store value.
- **history** (array) - Access the array of previous states.
### Methods
- **update(updater)** - Performs a functional update on the state.
- **lock()** - Prevents modifications and returns a lock symbol.
- **unlock(id)** - Unlocks the store using the symbol returned by lock().
- **subscribe(cb)** - Subscribes to changes; returns an unsubscribe function.
```
--------------------------------
### Create a store instance
Source: https://github.com/craxjs/crax/blob/main/packages/docs-site/docs/guide/features/state-management.mdx
Initialize a store with a default value using createStore.
```typescript
// src/stores/theme.ts
import { createStore } from '@crax/store'
export const themeStore = createStore<'light' | 'dark'>('light')
```
--------------------------------
### Using the Image component
Source: https://github.com/craxjs/crax/blob/main/packages/docs-site/docs/guide/features/image-optimization.mdx
Demonstrates basic usage with CDN URLs and local imports processed by vite-imagetools.
```tsx
import { Image } from '@crax/image'
// CDN image
// Local image with vite-imagetools
import logoUrl from '@/assets/logo.png?w=200&format=webp'
```
--------------------------------
### Implement view transitions with useViewTransition
Source: https://github.com/craxjs/crax/blob/main/packages/docs-site/docs/guide/features/view-transitions.mdx
Wraps navigation logic within the startTransition callback to trigger native view transitions.
```tsx
import { useViewTransition } from '@crax/hooks'
import { useRouter } from '@crax/router'
export default function NavBar() {
const { startTransition } = useViewTransition()
const router = useRouter()
return (
)
}
```
--------------------------------
### Configure local image assets
Source: https://github.com/craxjs/crax/blob/main/packages/docs-site/docs/guide/skill.mdx
Import local images with query parameters to generate optimized formats and blur placeholders.
```tsx
import heroUrl from '@/assets/hero.jpg?w=1200&format=webp'
import heroBlur from '@/assets/hero.jpg?w=24&blur=3&format=webp&inline'
```
--------------------------------
### Local Caddy Deployment
Source: https://github.com/craxjs/crax/blob/main/packages/docs-site/docs/guide/features/deploy.mdx
Running the application locally using the Caddy server.
```bash
pnpm build
caddy run --config Caddyfile
```
--------------------------------
### Deploy to GitHub Pages
Source: https://github.com/craxjs/crax/blob/main/packages/docs-site/README.md
Deploys the site to GitHub Pages using the gh-pages package.
```bash
pnpm deploy
```
--------------------------------
### Configure entry point for SSG
Source: https://github.com/craxjs/crax/blob/main/packages/docs-site/docs/guide/features/ssg.mdx
Update src/main.tsx to use ViteSSG and provide the route paths discovered by Crax.
```tsx
import { ViteSSG } from 'vite-ssg'
import App from './App'
import { getRoutes } from '@crax/router'
// getRoutes() is resolved at call time (SSG/prerender tooling always wants
// the current page tree, never a stale cached list). Filter out dynamic
// segments (":id", "*") unless you also generate the concrete paths to
// prerender for them (e.g. fetch a list of slugs and map each to its own path).
const routes = getRoutes()
.filter((route) => !route.isDynamic)
.map((route) => route.path)
export const createApp = ViteSSG(App, { routes })
```
--------------------------------
### Build and Deploy Crax Application
Source: https://github.com/craxjs/crax/blob/main/templates/v1/skills/crax/SKILL.md
Commands to build the project and deploy using Docker or static hosting services.
```bash
pnpm build
```
```bash
# Docker
docker build -t my-app .
docker run -p 3000:80 my-app
# Static hosting (Vercel, Netlify, Cloudflare Pages)
# Just point to dist/ directory
```
--------------------------------
### Configure image settings
Source: https://github.com/craxjs/crax/blob/main/packages/docs-site/docs/guide/features/image-optimization.mdx
Define global image settings in the configuration file. Note that deviceSizes and defaultProps are currently reserved and not yet implemented.
```js
export default {
images: {
deviceSizes: [320, 640, 960, 1280],
formats: ['webp', 'avif'],
defaultProps: {
sizes: '(max-width: 640px) 100vw, 640px',
loading: 'lazy',
decoding: 'async',
},
},
}
```
--------------------------------
### Project File Structure
Source: https://github.com/craxjs/crax/blob/main/packages/docs-site/docs/guide/examples/pokedex.mdx
Overview of the directory layout for the Pokedex application.
```text
src/
pages/
page.tsx # Home, modal quick view
not-found.tsx # 404 page
pokemon/
page.tsx # All Pokemon list
[id].tsx # Pokemon detail
favorites/
page.tsx # Favorites list
stores/
favorites.ts # createStore([]), toggleFavorite()
lib/
api.ts # fetchPokemonList, fetchPokemon, pokemonArtwork
```
--------------------------------
### Link Component Usage
Source: https://github.com/craxjs/crax/blob/main/templates/v1/skills/crax/SKILL.md
Demonstrates various prefetching strategies and view transition configuration for the Link component.
```tsx
import { Link } from '@crax/router'
// Smart (default): prefetch on hover/focus/pointerdown, or when link enters viewport
Dashboard
// Foresight: hover + cursor trajectory prediction (+ pointerdown fallback)
Pricing
// None: plain react-router link, no prefetch
Terms
// With view transition (auto-disabled if the OS prefers reduced motion)
About
```
--------------------------------
### Programmatic Navigation and Prefetching
Source: https://github.com/craxjs/crax/blob/main/packages/docs-site/docs/guide/skill.mdx
Use useRouter for programmatic navigation and the prefetch function to manually trigger data loading.
```tsx
const router = useRouter()
async function onSubmit() {
prefetch({ path: '/dashboard' })
await saveForm()
router.push('/dashboard')
}
```
--------------------------------
### View project structure
Source: https://github.com/craxjs/crax/blob/main/packages/docs-site/docs/guide/start/getting-started.mdx
Overview of the file system layout for a standard CRAX project.
```text
my-app/
├── .crax/ # Framework source, yours to read and modify
│ ├── router/ # File-based routing
│ ├── store/ # Global state (createStore, useStore)
│ ├── image/ # Image and Picture components
│ ├── seo/ # Head component for document metadata
│ ├── hooks/ # useForesight and other hooks
│ ├── pwa/ # PWA icon and manifest generation
│ ├── scripts/ # Build-time scripts
│ ├── types/ # Shared TypeScript types
│ └── utils/ # Internal utilities
├ src/
│ ├── pages/
│ │ ├── page.tsx # Home page -> /
│ │ └── not-found.tsx # 404 page
│ ├── stores/ # Centralized state
│ │ └── index.ts # All stores in one file (or split per feature)
│ ├── components/ # Shared UI components
│ ├── App.tsx # Root component, QueryClient setup
│ ├── main.tsx # Entry point
│ └── index.css # Global styles
├ crax.config.mjs # Your config
├ vite.config.ts # Vite config (do not touch)
└ package.json
```
--------------------------------
### Configure Project Settings
Source: https://github.com/craxjs/crax/blob/main/packages/docs-site/docs/guide/skill.mdx
Define site-wide settings including image optimization and Open Graph metadata in crax.config.mjs.
```js
export default {
siteUrl: 'https://example.com',
pagesDir: 'src/pages',
pageExtensions: ['tsx'],
images: {
deviceSizes: [320, 640, 960, 1280],
formats: ['webp', 'avif'],
defaultProps: {
sizes: '(max-width: 640px) 100vw, 640px',
loading: 'lazy',
decoding: 'async',
},
},
og: {
enabled: true,
template: 'default',
width: 1200,
height: 630,
font: 'Inter',
outputDir: 'dist/og',
},
}
```
--------------------------------
### Define multiple stores in a single file
Source: https://github.com/craxjs/crax/blob/main/packages/docs-site/docs/guide/features/state-management.mdx
Organize small projects by grouping store definitions in a single index file.
```typescript
// src/stores/index.ts
import { createStore } from '@crax/store'
export const themeStore = createStore<'light' | 'dark'>('light')
export const authStore = createStore({ user: null, isLoggedIn: false })
export const cartStore = createStore<{ id: number; qty: number }[]>([])
```
--------------------------------
### Store Instance Methods and Properties
Source: https://github.com/craxjs/crax/blob/main/packages/docs-site/docs/guide/features/state-management.mdx
Direct access methods for interacting with stores outside of React components.
```APIDOC
## Store Instance API
### Properties
- **value** (any) - The current state value. Can be read or written directly.
- **history** (Array) - An array tracking the history of state changes.
### Methods
- **update(updater: (prev: T) => T)** - Performs a functional update on the store state.
- **lock()** - Returns a lockId to prevent modifications during critical operations.
- **unlock(lockId)** - Releases the lock associated with the provided lockId.
- **subscribe(callback: () => void)** - Subscribes to store changes and returns an unsubscribe function.
```
--------------------------------
### Importing Modules with Aliases
Source: https://github.com/craxjs/crax/blob/main/packages/docs-site/docs/guide/skill.mdx
Use the @/ alias for local project files and @crax/ prefixes for framework modules to maintain consistent import paths.
```tsx
// Framework modules — use alias
import { Link, useRouter, Outlet } from '@crax/router'
import { createStore, useStore, useStoreEffect } from '@crax/store'
import { Image, Picture } from '@crax/image'
import { Head } from '@crax/seo'
import { useViewTransition } from '@crax/hooks/use-view-transition'
// Your code — use @/ alias
import { authStore } from '@/stores/auth'
import { Button } from '@/components/Button'
import { formatDate } from '@/utils/format'
```
--------------------------------
### File-based routing mapping
Source: https://github.com/craxjs/crax/blob/main/README.md
Demonstrates how file paths in the src/pages directory correspond to URL routes.
```text
src/pages/page.tsx → /
src/pages/home.tsx → /home
src/pages/users/page.tsx → /users
src/pages/users/[id].tsx → /users/:id
```
--------------------------------
### Docker and Caddy Configuration
Source: https://github.com/craxjs/crax/blob/main/packages/docs-site/docs/guide/features/deploy.mdx
Standard Dockerfile and Caddyfile for containerizing a Crax application.
```dockerfile
FROM node:20-alpine AS builder
WORKDIR /app
COPY package*.json ./
RUN npm install
COPY . .
RUN npm run build
FROM caddy:alpine AS runner
COPY --from=builder /app/dist /srv
COPY Caddyfile /etc/caddy/Caddyfile
EXPOSE 80
CMD ["caddy", "run", "--config", "/etc/caddy/Caddyfile", "--adapter", "caddyfile"]
```
```caddyfile
:80 {
root * /srv
encode gzip
file_server
try_files {path} /index.html
}
```
--------------------------------
### useRouter Hook Implementation
Source: https://github.com/craxjs/crax/blob/main/templates/v1/skills/crax/SKILL.md
Shows how to access navigation methods and route information using the unified useRouter hook.
```tsx
import { useRouter } from '@crax/router'
function Navigation() {
const router = useRouter()
return (
Current path: {router.pathname}
Query: {router.searchParams.get('q')}
User ID: {router.params.id}
)
}
```
--------------------------------
### Add site icons
Source: https://github.com/craxjs/crax/blob/main/packages/docs-site/docs/guide/features/seo.mdx
Include favicon and apple-touch-icon links within the Head component.
```tsx
```
--------------------------------
### Implement responsive images
Source: https://github.com/craxjs/crax/blob/main/packages/docs-site/docs/guide/skill.mdx
Use Image and Picture components for optimized, responsive media with support for custom sizes and art direction.
```tsx
import { Image, Picture } from '@crax/image'
// Basic usage
// With custom sizes
// Art-directed: different crops per breakpoint
// Full-width with priority (LCP image)
// Local image with blur placeholder
```
--------------------------------
### Create a new page
Source: https://github.com/craxjs/crax/blob/main/packages/docs-site/docs/guide/start/getting-started.mdx
Add a new file in the src/pages directory to automatically register a new route.
```tsx
export default function AboutPage() {
return
About
}
```
--------------------------------
### Client-Side Navigation with Link
Source: https://github.com/craxjs/crax/blob/main/packages/docs-site/docs/guide/skill.mdx
Use the Link component for navigation. Supports automatic prefetching strategies and view transitions.
```tsx
import { Link, useRouter, prefetch } from '@crax/router'
// Smart prefetch: hover, focus, pointerdown, or viewport visibility
Dashboard
// Foresight: predict intent from cursor movement
Pricing
// No prefetch
Terms
// With view transitions
About
```
--------------------------------
### Access store API methods
Source: https://github.com/craxjs/crax/blob/main/templates/v1/skills/crax/SKILL.md
Directly interact with the store instance for manual state management and subscription.
```tsx
const store = createStore(0)
store.value // get current value
store.value = 5 // set value
store.update(prev => prev + 1) // functional update
store.history // previous states array
store.lock() // returns symbol, prevents modifications
store.unlock(id) // unlock with the symbol
store.subscribe(cb) // subscribe to changes, returns unsubscribe fn
```
--------------------------------
### Define custom transition styles
Source: https://github.com/craxjs/crax/blob/main/packages/docs-site/docs/guide/features/view-transitions.mdx
Configures CSS animations for view transitions in the global stylesheet.
```css
::view-transition-old(root),
::view-transition-new(root) {
animation-duration: 150ms;
}
```
--------------------------------
### Navigate with Link component
Source: https://github.com/craxjs/crax/blob/main/packages/docs-site/docs/guide/features/routing.mdx
Use the Link component for client-side navigation. Prefetching strategies can be configured via the prefetch prop.
```tsx
import { Link } from '@crax/router'
// Smart (default): prefetches on hover, focus, or pointerdown, plus a
// viewport-observation baseline for links that are never hovered
Dashboard
// Foresight, predicts user intent from cursor movement (hover/pointerdown also prefetch directly)
Pricing
// None, plain client-side navigation
Terms
```
--------------------------------
### Use the useStore hook
Source: https://github.com/craxjs/crax/blob/main/packages/create-crax-app/template/skills/crax/SKILL.md
Access state and a setter function, supporting functional updates.
```tsx
import { useStore } from '@crax/store'
function ThemeToggle() {
const [theme, setTheme] = useStore(themeStore)
return (
)
}
```
```tsx
const [count, setCount] = useStore(counterStore)
setCount(prev => prev + 1)
```
--------------------------------
### Display navigation feedback
Source: https://github.com/craxjs/crax/blob/main/templates/v1/skills/crax/SKILL.md
Use useNavigation from @crax/router to track the state of route transitions. Only effective when routes utilize loader functions.
```tsx
import { useNavigation } from '@crax/router'
function ProgressBar() {
const navigation = useNavigation()
return navigation.state === 'loading' ? (
) : null
}
```
--------------------------------
### Implement blur-up placeholders for local images
Source: https://github.com/craxjs/crax/blob/main/packages/docs-site/docs/guide/features/image-optimization.mdx
Generates a tiny inlined blur placeholder at compile time using vite-imagetools and passes it to the component.
```tsx
import heroUrl from '@/assets/hero.jpg?w=1200&format=webp'
import heroImg from '@/assets/hero.jpg?w=1200&format=webp;avif&as=picture'
import heroBlur from '@/assets/hero.jpg?w=24&blur=3&format=webp&inline'
```
--------------------------------
### Check View Transition API support
Source: https://github.com/craxjs/crax/blob/main/packages/docs-site/docs/guide/features/view-transitions.mdx
Uses the isSupported boolean from the hook to verify if the browser supports the native API.
```tsx
const { isSupported } = useViewTransition()
// isSupported is true when document.startViewTransition is available
```
--------------------------------
### Implement View Transitions
Source: https://github.com/craxjs/crax/blob/main/packages/docs-site/docs/guide/skill.mdx
Utilize the useViewTransition hook to trigger native browser page transitions via the View Transitions API.
```tsx
import { useViewTransition } from '@crax/hooks/use-view-transition'
import { Link } from '@crax/router'
function Nav() {
const { startViewTransition } = useViewTransition()
return (
<>
About
>
)
}
```
--------------------------------
### Define Multiple Stores
Source: https://github.com/craxjs/crax/blob/main/templates/v1/skills/crax/SKILL.md
Initialize independent stores for managing related application state.
```tsx
const themeStore = createStore<'light' | 'dark'>('light')
const sidebarStore = createStore(true)
const notificationsStore = createStore([])
```
--------------------------------
### Configure PWA in crax.config.mjs
Source: https://github.com/craxjs/crax/blob/main/packages/docs-site/docs/guide/features/pwa.mdx
Enable PWA features and define manifest metadata in the project configuration file.
```js
// crax.config.mjs
export default {
pwa: {
enabled: true,
name: 'My App',
shortName: 'App',
themeColor: '#f59e0b',
backgroundColor: '#ffffff',
iconPath: 'logo.png', // relative to public/
startUrl: '/',
display: 'standalone',
},
}
```
--------------------------------
### Add meta tags
Source: https://github.com/craxjs/crax/blob/main/packages/docs-site/docs/guide/features/seo.mdx
Include standard meta tags for SEO and viewport configuration within the Head component.
```tsx
```
--------------------------------
### Generate PWA icons
Source: https://github.com/craxjs/crax/blob/main/packages/docs-site/docs/guide/features/cli-commands.mdx
Generates PWA icons from a logo file; requires pwa.enabled set to true in configuration.
```bash
npx @craxjs/crax pwa
```
--------------------------------
### Configure PWA settings
Source: https://github.com/craxjs/crax/blob/main/packages/docs-site/docs/guide/features/configuration.mdx
Settings for Progressive Web App features, including theme colors and display modes.
```js
export default {
pwa: {
enabled: true,
name: 'My App',
shortName: 'App',
themeColor: '#f59e0b',
backgroundColor: '#ffffff',
iconPath: 'logo.png',
startUrl: '/',
display: 'standalone',
},
}
```
--------------------------------
### Documentation directory structure
Source: https://github.com/craxjs/crax/blob/main/packages/docs-site/README.md
Overview of the file organization within the docs directory.
```text
docs/
index.tsx # Home page (custom React component)
home.css # Home page styles
_nav.json # Top navigation
guide/
_meta.json
start/
getting-started.md
introduction.md
features/
routing.md
image-optimization.md
state-management.md
configuration.md
cli-commands.md
data-fetching.md
deploy.md
pwa.md
seo.md
ssg.md
view-transitions.md
index.md
examples/
pokedex.md
```
--------------------------------
### Implement route loaders for pre-rendering
Source: https://github.com/craxjs/crax/blob/main/packages/docs-site/docs/guide/skill.mdx
Define a loader function to fetch data before the route renders and use useLoaderData to access it.
```tsx
// src/pages/users/[id].tsx
import { useLoaderData, useNavigation } from '@crax/router'
export async function loader({ params }: { params: { id: string } }) {
const user = await fetch(`/api/users/${params.id}`).then(r => r.json())
return { user }
}
export default function UserPage() {
const { user } = useLoaderData() as { user: { name: string } }
const navigation = useNavigation()
return (
<>
{navigation.state === 'loading' && }
{user.name}
>
)
}
```
--------------------------------
### useViewTransition Hook
Source: https://github.com/craxjs/crax/blob/main/packages/create-crax-app/template/skills/crax/SKILL.md
Provides access to the View Transitions API for native browser page transitions.
```APIDOC
## useViewTransition Hook
### Description
Enables native browser page transitions. Falls back to a plain callback on unsupported browsers.
### Usage
- `startTransition(callback)`: Triggers a state update that initiates the transition.
- ``: Prop available on the Router Link component to trigger transitions on navigation.
```
--------------------------------
### Access router programmatically
Source: https://github.com/craxjs/crax/blob/main/packages/docs-site/docs/guide/features/routing.mdx
Use the useRouter hook to access router state and perform programmatic navigation.
```tsx
import { useRouter } from '@crax/router'
function MyComponent() {
const router = useRouter()
return (
)
}
```
--------------------------------
### Enumerating Routes for SSG
Source: https://github.com/craxjs/crax/blob/main/packages/docs-site/docs/guide/skill.mdx
Use getRoutes to retrieve a list of all defined routes for static site generation purposes.
```tsx
import { getRoutes } from '@crax/router'
const routes = getRoutes()
// Returns [{ path: "/", filePath: "...", isDynamic: false }, ...]
```
--------------------------------
### Fetch server state with React Query
Source: https://github.com/craxjs/crax/blob/main/packages/docs-site/docs/guide/skill.mdx
Utilize the pre-configured React Query hook to manage server state within components.
```tsx
import { useQuery } from '@tanstack/react-query'
function UserProfile({ userId }: { userId: string }) {
const { data, isLoading } = useQuery({
queryKey: ['user', userId],
queryFn: () => fetch(`/api/users/${userId}`).then(r => r.json()),
})
if (isLoading) return
Loading...
return
{data.name}
}
```
--------------------------------
### Toggle state with useStore
Source: https://github.com/craxjs/crax/blob/main/templates/v1/skills/crax/SKILL.md
Implement state toggling using the setter returned by useStore.
```tsx
import { useStore } from '@crax/store'
function ThemeToggle() {
const [theme, setTheme] = useStore(themeStore)
return (
)
}
```
--------------------------------
### Configure React Query in App.tsx
Source: https://github.com/craxjs/crax/blob/main/packages/docs-site/docs/guide/features/data-fetching.mdx
The QueryClient is pre-configured with default staleTime and retry settings. ReactQueryDevtools are included for development debugging.
```tsx
// src/App.tsx, already set up for you
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
import { ReactQueryDevtools } from '@tanstack/react-query-devtools'
const queryClient = new QueryClient({
defaultOptions: {
queries: { staleTime: 1000 * 60, retry: 1 },
},
})
export function App() {
return (
)
}
```
--------------------------------
### Define stores in larger projects
Source: https://github.com/craxjs/crax/blob/main/packages/docs-site/docs/guide/skill.mdx
Organize state in separate files with exported helper functions for state updates.
```tsx
// src/stores/auth.ts
import { createStore } from '@crax/store'
export const authStore = createStore({
user: null as { id: string; name: string } | null,
isLoggedIn: false,
})
export function login(name: string) {
authStore.value = { user: { id: '1', name }, isLoggedIn: true }
}
export function logout() {
authStore.value = { user: null, isLoggedIn: false }
}
```
--------------------------------
### Implement View Transitions
Source: https://github.com/craxjs/crax/blob/main/templates/v1/skills/crax/SKILL.md
Trigger view transitions using the Link component prop or the useViewTransition hook. The hook falls back to a plain callback on unsupported browsers.
```tsx
import { useViewTransition } from '@crax/hooks'
import { Link } from '@crax/router'
function Nav() {
const { startTransition } = useViewTransition()
const handleClick = () => {
startTransition(() => {
// state update that triggers the transition
})
}
return (
<>
{/* Via Link prop */}
About
{/* Via hook */}
>
)
}
```
--------------------------------
### Project Structure Overview
Source: https://github.com/craxjs/crax/blob/main/packages/create-crax-app/template/README.md
Visual representation of the standard Crax project directory layout.
```text
src/
pages/ # File-based routes
page.tsx # Home page -> /
App.tsx # Root component
main.tsx # Entry point
index.css # Global styles (Tailwind)
.crax/ # Framework source, yours to read and modify
```
--------------------------------
### Optimizing local images
Source: https://github.com/craxjs/crax/blob/main/packages/docs-site/docs/guide/features/image-optimization.mdx
Using vite-imagetools imports to ensure local files are processed for optimization.
```tsx
import heroUrl from '@/assets/hero.jpg?w=1200&format=webp'
```
--------------------------------
### Define default configuration
Source: https://github.com/craxjs/crax/blob/main/packages/docs-site/docs/guide/features/configuration.mdx
The base configuration file structure using the CraxConfig type definition.
```js
// crax.config.mjs
/** @type {import('./.crax/types/config.types.ts').CraxConfig} */
export default {
siteUrl: 'https://example.com',
pagesDir: 'src/pages',
pageExtensions: ['tsx'],
images: {
deviceSizes: [320, 640, 960, 1280],
formats: ['webp', 'avif'],
defaultProps: {
sizes: '(max-width: 640px) 100vw, 640px',
loading: 'lazy',
decoding: 'async',
},
},
}
```
--------------------------------
### Manage Document Head with SEO Component
Source: https://github.com/craxjs/crax/blob/main/packages/docs-site/docs/guide/skill.mdx
Use the Head component to inject meta tags, titles, and canonical links into the document head.
```tsx
import { Head } from '@crax/seo'
function AboutPage() {
return (
<>
About - My App
About
>
)
}
```
--------------------------------
### Define View Transition CSS
Source: https://github.com/craxjs/crax/blob/main/templates/v1/skills/crax/SKILL.md
Apply CSS animations to the view transition pseudo-elements to customize the transition effect.
```css
/* src/index.css */
::view-transition-old(root) {
animation: fade-out 0.2s ease-out;
}
::view-transition-new(root) {
animation: fade-in 0.2s ease-in;
}
```
--------------------------------
### Render a Picture component
Source: https://github.com/craxjs/crax/blob/main/packages/docs-site/docs/guide/features/image-optimization.mdx
Uses vite-imagetools ?as=picture imports to render a picture element with multiple format sources.
```tsx
import heroImg from '@/assets/hero.jpg?w=1200&format=webp;avif&as=picture'
```
--------------------------------
### Fetch data in a component
Source: https://github.com/craxjs/crax/blob/main/packages/docs-site/docs/guide/features/data-fetching.mdx
Use the useQuery hook to fetch and manage data state within a React component.
```tsx
import { useQuery } from '@tanstack/react-query'
export default function UsersPage() {
const { data, isLoading, error } = useQuery({
queryKey: ['users'],
queryFn: () => fetch('/api/users').then(r => r.json()),
})
if (isLoading) return
Loading...
if (error) return
Error loading users.
return (
{data?.map(user => (
{user.name}
))}
)
}
```
--------------------------------
### Prefetch routes programmatically
Source: https://github.com/craxjs/crax/blob/main/packages/docs-site/docs/guide/features/routing.mdx
Use the prefetch function to warm route chunks before navigating programmatically.
```tsx
import { useRouter, prefetch } from '@crax/router'
async function onSubmit() {
prefetch({ path: '/dashboard' })
await saveForm()
router.push('/dashboard')
}
```
--------------------------------
### Run type check
Source: https://github.com/craxjs/crax/blob/main/packages/docs-site/docs/guide/features/cli-commands.mdx
Executes tsc --noEmit to validate project types without generating output files.
```bash
pnpm typecheck
```
--------------------------------
### useRouter Hook
Source: https://github.com/craxjs/crax/blob/main/templates/v1/skills/crax/SKILL.md
A unified hook that wraps React Router's navigation and location utilities.
```APIDOC
## useRouter Hook
### Description
Provides a unified interface for navigation and accessing route information.
### Methods
- **router.push(path)** - Navigate to the specified path.
- **router.replace(path)** - Replace the current history entry.
- **router.back()** - Navigate back one step.
### Properties
- **router.pathname** (string) - The current path.
- **router.searchParams** (URLSearchParams) - The current query parameters.
- **router.params** (Record) - The current route parameters.
```