### Start Nue.js Development Server (Bash)
Source: https://github.com/nuejs/nue/blob/master/packages/www/docs/getting-started.md
Starts the development server for a Nue.js project, typically serving at http://localhost:4000. Assumes nuekit is installed globally.
```bash
nue dev # Starts serving at http://localhost:4000
```
--------------------------------
### Install and Create a Nue.js Project (Bash)
Source: https://github.com/nuejs/nue/blob/master/packages/www/docs/getting-started.md
Installs Bun, globally installs the Nuekit package, and creates a new Nue.js project. Supports template types like 'blog', 'minimal', 'spa', and 'full'.
```bash
# Install Bun 1.2+ (if you don't have it yet)
curl -fsSL https://bun.sh/install | bash
# Install Nuekit globally
bun install --global nuekit
# Create your first project
nue create blog # or minimal, spa, full
```
--------------------------------
### Switch to Global Nuekit Installation (Bash)
Source: https://github.com/nuejs/nue/blob/master/packages/www/docs/getting-started.md
Removes the globally installed `nuekit` package and then installs the latest version. This is the final step after confirming a new version works correctly in local testing.
```bash
bun remove --global nuekit
bun install --global nuekit@latest
```
--------------------------------
### Run Nue Commands with Bunx for Local Testing (Bash)
Source: https://github.com/nuejs/nue/blob/master/packages/www/docs/getting-started.md
Executes Nue.js commands using `bunx`, which is recommended for testing new versions locally without affecting a global installation. This approach allows for safe migration.
```bash
touch index.html
bunx nue serve
bunx nue build
```
--------------------------------
### Quick Start: GET and POST Route Handlers
Source: https://github.com/nuejs/nue/blob/master/packages/www/docs/server-api.md
Basic setup for handling GET and POST requests using Nueserver route handlers. Demonstrates retrieving data with JSON responses and creating resources with custom status codes. No external dependencies required beyond Nueserver.
```javascript
get('/api/users', async (c) => {
return c.json([{ id: 1, name: 'Alice' }])
})
post('/api/users', async (c) => {
const user = await c.req.json()
return c.json(user, 201)
})
```
--------------------------------
### Complete State Setup Configuration Example
Source: https://github.com/nuejs/nue/blob/master/packages/www/docs/state-api.md
Presents a comprehensive example of `state.setup()` configuration, including route patterns, query parameters, session and local storage, in-memory state, emit-only properties, and automatic link handling.
```javascript
state.setup({
route: '/shop/:category/:product',
query: ['search', 'color', 'size', 'page'],
session: ['user', 'cart'],
local: ['theme', 'currency'],
memory: ['loading', 'errors', 'removeId'],
emit_only: ['deleted', 'saved'],
autolink: true
})
```
--------------------------------
### Nue.js Project File Structure Example
Source: https://github.com/nuejs/nue/blob/master/packages/www/docs/website-development.md
An example of the typical file structure generated by `nue create blog`. It illustrates the separation of concerns between configuration, global layouts, content, and design files.
```text
├── site.yaml # global configuration
├── layout.html # shared header and footer
├── index.md # front page
├── index.css # design
└── posts/
├── header.html # blog post hero section
├── first.md # example post
└── second.md # example post
```
--------------------------------
### Update Nuekit Package Globally (Bash)
Source: https://github.com/nuejs/nue/blob/master/packages/www/docs/getting-started.md
Updates the global `nuekit` command to the latest version available on npm. This command ensures you have the most recent features and fixes.
```bash
bun install --global nuekit@latest
```
--------------------------------
### Setup and Run Nue from Source (Shell)
Source: https://github.com/nuejs/nue/blob/master/packages/www/docs/contributing.md
This snippet demonstrates how to clone the Nue repository, install dependencies using Bun, and run the local nuekit for testing changes. It's essential for developers who want to test their modifications directly within the project.
```shell
git clone https://github.com/nuejs/nue
cd nue
bun install
# Test with a template using local nuekit
cd packages/templates/full
../../nuekit/src/cli.js
→ Nue 2.0-beta • Bun 1.2.22
→ Serving on http://localhost:4000/
```
--------------------------------
### Install Nue CLI
Source: https://github.com/nuejs/nue/blob/master/packages/www/docs/cli.md
Installs the Nuekit CLI globally using Bun. This command makes the `nue` executable available system-wide for development and building.
```bash
bun install --global nuekit
```
--------------------------------
### Starting with Markdown Content
Source: https://github.com/nuejs/nue/blob/master/packages/www/docs/website-development.md
Illustrates the initial step of writing content using standard Markdown, focusing on the text and structure without immediate concern for layout or styling. This promotes a content-first workflow.
```markdown
# About our company
We believe technology should serve people, not the other way around.
## Our mission
To build software that makes complex things simple.
```
--------------------------------
### Create and start SPA project in Nue
Source: https://github.com/nuejs/nue/blob/master/packages/www/docs/spa-development.md
Initialize a new Nue SPA project with the project template and start the development server with hot reload support for all assets.
```bash
nue create spa
```
```bash
nue dev
```
--------------------------------
### Complete YAML Configuration Example
Source: https://github.com/nuejs/nue/blob/master/packages/www/docs/yaml-syntax.md
Comprehensive example demonstrating supported YAML features including nested objects, arrays, multi-line strings, special characters in keys, and various data types. Shows application configuration, database settings, API routes, security credentials, and server configurations.
```yaml
# Application configuration
app:
name: My Application
version: 1.2.0
debug: false
launched: 2024-01-15
# Database settings
database:
host: localhost
port: 5432
credentials:
username: admin
password:
connection_string:
postgresql://admin@localhost:5432/myapp
?ssl=true&timeout=10
# API routes - special characters in keys
/api/users/:id: getUserHandler
/api/posts: getPostsHandler
/api/auth/login: loginHandler
# Security
api_keys:
github: ghp_xxxxxxxxxxxxxxxxxxxx
stripe: sk-test_#################
aws: AKIA#############
# Features array
features: [auth, analytics, caching]
experimental:
- new-dashboard
- dark-mode
- websockets
# Responsive design breakpoints
breakpoints:
@media (max-width: 768px): mobile
@media (max-width: 1024px): tablet
@media (min-width: 1025px): desktop
# Multi-line content
welcome_message:
Welcome to our application!
This message spans multiple lines
and preserves blank lines and
indentation exactly as written.
# Server configuration
servers:
- name: web-01
ip: 192.168.1.10
active: true
roles: [web, api]
- name: web-02
ip: 192.168.1.11
active: false
roles: [web]
- name: db-01
ip: 192.168.1.20
active: true
roles: [database, cache]
# Metadata
_internal:
build_number: 4567
commit: abc123def
timestamp: 2024-01-15T10:30:00Z
```
--------------------------------
### Homepage Structure with HTML
Source: https://github.com/nuejs/nue/blob/master/packages/www/docs/website-development.md
Provides an example of a homepage structure implemented entirely with HTML, showcasing sections for a hero banner and featured posts. It uses the `:each` directive to display a sliced subset of the 'blog' collection.
```html
Our blog
Stay updated with the latest insights on design and development.
```
--------------------------------
### Nuedom Installation (as Library)
Source: https://github.com/nuejs/nue/blob/master/packages/www/docs/nuedom.md
Command to install Nuedom directly as a library using Bun. This is suitable for experiments and prototypes when not using the full Nuekit.
```bash
bun install nuedom
```
--------------------------------
### SPA Root Component Setup with NueJS State (HTML)
Source: https://github.com/nuejs/nue/blob/master/packages/www/docs/state-api.md
An example of a root SPA component in NueJS, demonstrating the setup of state management including query parameters, emit-only events, memory storage, route parameters, and autolinking. It also includes session check and dynamic component mounting based on state.
```html
```
--------------------------------
### Next.js Backend Dependencies Installation
Source: https://github.com/nuejs/nue/blob/master/packages/www/docs/migration.md
Installs required npm packages for Next.js backend setup including Vercel services (KV, Postgres), Drizzle ORM with CLI, Next-Auth beta, and TypeScript types. These dependencies are necessary for building a complete backend infrastructure but result in a 1.4GB project size.
```bash
npm install @vercel/kv @vercel/postgres
npm install drizzle-orm drizzle-kit
npm install next-auth@beta @auth/drizzle-adapter
npm install @types/node
```
--------------------------------
### Install Nueyaml Package
Source: https://github.com/nuejs/nue/blob/master/packages/www/docs/nueyaml.md
Provides the command to install the Nueyaml library using the 'bun' package manager. This is the initial step required to use Nueyaml for parsing configuration files.
```bash
bun install nueyaml
```
--------------------------------
### Nuemark Block Syntax Examples with Various Classes
Source: https://github.com/nuejs/nue/blob/master/packages/www/docs/nuemark-syntax.md
Provides examples of using Nuemark's block syntax with different class names. These examples show how to apply custom classes like 'warning', 'testimonial', 'pricing-tier', and 'photo-gallery' to content blocks for varied semantic and stylistic purposes.
```md
[.warning] →
...
[.testimonial] →
...
[.pricing-tier] →
...
[.photo-gallery] →
...
```
--------------------------------
### Install Nuestate using Bun
Source: https://github.com/nuejs/nue/blob/master/packages/www/docs/nuestate.md
Provides the command to install the Nuestate library using the Bun package manager.
```bash
bun install nuestate
```
--------------------------------
### Troubleshoot Nue CLI 'Command not found'
Source: https://github.com/nuejs/nue/blob/master/packages/www/docs/cli.md
Provides steps to resolve the 'command not found' error after installing Nuekit. It includes checking the Bun installation and its presence in the system's PATH, and ensuring global installation of `nuekit`.
```bash
# Check if Bun is in PATH
which bun
# Install globally
bun install --global nuekit
```
--------------------------------
### Nuemark Grid Layout Example
Source: https://github.com/nuejs/nue/blob/master/packages/www/docs/nuemark-syntax.md
Shows a Nuemark example for creating a grid layout. Using a 'grid' class on a block, followed by headings, generates a structure suitable for multi-column responsive layouts defined by CSS.
```markdown
[.grid]
### Feature One
First feature description
### Feature Two
Second feature description
### Feature Three
Third feature description
```
--------------------------------
### Next.js: Installing Business Logic Packages (Bash)
Source: https://github.com/nuejs/nue/blob/master/packages/www/docs/migration.md
Installs essential packages for managing business logic in Next.js applications, including state management, data fetching, form handling, and validation.
```bash
npm add @tanstack/react-query zustand react-hook-form
npm add -D @tanstack/react-query-devtools
npm add @hookform/resolvers zod
```
--------------------------------
### Create Minimal Nue Project
Source: https://github.com/nuejs/nue/blob/master/packages/www/docs/project-structure.md
Command to create a minimal Nue project with just an HTML file and a stylesheet. This highlights Nue's zero-friction setup.
```bash
nue create minimal
```
--------------------------------
### Nuemark Content Structure Example
Source: https://github.com/nuejs/nue/blob/master/packages/www/docs/nuemark.md
This example demonstrates how Nuemark syntax is used to define a hero section with a heading, descriptive text, buttons, and an image. It highlights the clean, indentation-based structure for creating semantic HTML.
```markdown
[.hero]
# Content is king
Web design is 95% typography
[button "Learn more" href="/docs/"]
[button.primary "Get started" href="/get-started/"]
---
[image typography.png]
```
--------------------------------
### Nue Routing Examples with Directories
Source: https://github.com/nuejs/nue/blob/master/packages/www/docs/project-structure.md
Illustrates how Nue's routing handles files within directories, including index files for directory routes and catch-all routes for specific application paths.
```text
index.html → /
about.md → /about/
contact/index.md → /contact/
contact/thanks.md → /contact/thanks
app/index.html → /app/ (handles all /app/* routes)
admin/index.html → /admin/ (handles all /admin/* routes)
404.md → custom error page
```
--------------------------------
### Nue Frontend Imports Example
Source: https://github.com/nuejs/nue/blob/master/packages/www/docs/project-structure.md
Demonstrates how to use the configured import map in JavaScript to import modules from the '@shared/app' and '@shared/lib' directories.
```javascript
import { login } from 'app' // @shared/app/index.js
import * as d3 from 'lib/d3' // @shared/lib/d3.js
```
--------------------------------
### Nuemark Stack Layout Example
Source: https://github.com/nuejs/nue/blob/master/packages/www/docs/nuemark-syntax.md
Demonstrates a Nuemark example for creating a stack layout. Using a 'stack' class on a block, followed by headings, generates a structure for vertical arrangements with consistent spacing, typically styled by CSS.
```markdown
[.stack]
### Design
Focus on systematic design
### Engineering
Built for performance
### Content
Pure content structure
```
--------------------------------
### Middleware Patterns
Source: https://github.com/nuejs/nue/blob/master/packages/www/docs/server-api.md
Provides examples of common middleware patterns, including authentication, CORS, and logging.
```APIDOC
## Middleware Patterns
### Authentication Middleware
Checks for a valid authorization token in the request headers.
```javascript
use('/api/*', async (c, next) => {
const token = c.req.header('authorization')
if (!isValid(token)) { // Assuming isValid is a defined function
return c.json({ error: 'Invalid token' }, 401)
}
await next()
})
```
### CORS Middleware
Adds CORS headers to the response to allow cross-origin requests.
```javascript
use(async (c, next) => {
const response = await next()
response.headers.set('Access-Control-Allow-Origin', '*')
return response
})
```
### Logging Middleware
Logs the method, URL, and execution time of each request.
```javascript
use(async (c, next) => {
const start = Date.now()
const response = await next()
console.log(`${c.req.method} ${c.req.url} - ${Date.now() - start}ms`)
return response
})
```
```
--------------------------------
### Display Collections in Markdown
Source: https://github.com/nuejs/nue/blob/master/packages/www/docs/website-development.md
Demonstrates how to use a collection within Markdown content to create dynamic lists. It shows how to reference a collection and uses a placeholder for a custom component that will render the collection items.
```markdown
---
title: Latest blog posts
---
# Our blog
Stay updated with the latest insights on design and development.
[blog-entries]
---
[button "View all posts" href="/blog/"]
```
--------------------------------
### Nue Project Routing Examples
Source: https://github.com/nuejs/nue/blob/master/packages/www/docs/project-structure.md
Demonstrates how Nue maps file paths to URLs. HTML and Markdown files become pages, while CSS files are treated as stylesheets. Other file types are passed through.
```text
index.html → /
about.html → /about
blog/index.html → /blog/
blog/first-post.md → /blog/first-post/
```
--------------------------------
### GET /api/users
Source: https://github.com/nuejs/nue/blob/master/packages/www/docs/server-api.md
Retrieves a list of users. This is an example of a basic GET request handler.
```APIDOC
## GET /api/users
### Description
Retrieves a list of users.
### Method
GET
### Endpoint
/api/users
### Parameters
#### Path Parameters
None
#### Query Parameters
None
#### Request Body
None
### Request Example
None
### Response
#### Success Response (200)
- **id** (integer) - The unique identifier for the user.
- **name** (string) - The name of the user.
#### Response Example
```json
[
{
"id": 1,
"name": "Alice"
}
]
```
```
--------------------------------
### Define Global Route Handlers with Nueserver
Source: https://github.com/nuejs/nue/blob/master/packages/nueserver/README.md
This snippet demonstrates how to define global HTTP route handlers using Nueserver's simple API. It shows examples for GET and POST requests, as well as middleware using the `use` function. These handlers are directly available without explicit imports or server setup.
```javascript
get('/api/users', async (c) => {
const users = await c.env.users.getAll()
return c.json(users)
})
post('/api/users', async (c) => {
const data = await c.req.json()
const user = await c.env.users.create(data)
return c.json(user, 201)
})
use('/admin/*', async (c, next) => {
const auth = c.req.header('authorization')
if (!auth) return c.json({ error: 'Unauthorized' }, 401)
await next()
})
```
--------------------------------
### Nue Create Command
Source: https://github.com/nuejs/nue/blob/master/packages/www/docs/cli.md
Creates a new Nue project from a starter template. This is useful for quickly scaffolding a new website with predefined structures for different project types like 'minimal', 'blog', 'spa', or 'full'. After creation, navigate to the new directory and run `nue` to serve it.
```bash
# minimal, blog, spa, or full
nue create blog
```
--------------------------------
### Setting up Routing Configuration
Source: https://github.com/nuejs/nue/blob/master/packages/www/docs/state-api.md
Demonstrates how to configure routing parameters using `state.setup()` with the `route` option. Setting route parameters updates the URL path accordingly.
```javascript
state.setup({
route: '/app/:section/:id'
})
state.section = 'products' // URL: /app/products
state.id = '123' // URL: /app/products/123
```
--------------------------------
### Section-Specific Layout in Nue.js
Source: https://github.com/nuejs/nue/blob/master/packages/www/docs/website-development.md
Example of defining layout modules specific to a section, like the 'blog' directory. These modules in `blog/layout.html` override global layouts for pages within that section.
```text
blog/
├── layout.html # blog-specific modules
├── my-first-entry.md
├── form-follows-function.md
└── content-first.md
```
--------------------------------
### Nuekit Site Configuration Example
Source: https://context7.com/nuejs/nue/llms.txt
Illustrates a `site.yaml` file used for configuring a Nue project. This file defines site-wide settings including metadata, development server options, build parameters, hot module replacement, sitemap generation, RSS feed details, global data, component libraries, and server routes.
```yaml
# site.yaml - Project configuration
# Site metadata
title: My Website
description: A modern website built with Nue
url: https://example.com
# Development server
port: 8080
root: ./src
# Build settings
dist: ./.dist
ignore:
- node_modules
- .git
- '*.test.js'
# Hot module replacement
hmr: true
# Sitemap generation
sitemap:
enabled: true
exclude:
- /admin/*
- /api/*
# RSS feed
rss:
enabled: true
title: My Blog
description: Latest posts
path: /feed.xml
# Global data available to all pages
globals:
brand: Acme Corp
year: 2024
social:
twitter: '@acme'
github: 'acme'
# Component libraries
libs:
- ./components/*.html
- ./layouts/*.html
# Server routes
server: ./api.js
```
--------------------------------
### Nueyaml Example Configurations
Source: https://github.com/nuejs/nue/blob/master/packages/www/docs/nueyaml.md
Illustrates the practical application of Nueyaml for writing complex configurations. It showcases features like handling special characters in property names, defining responsive breakpoints, multi-line string support, and mixed data types within a structured object.
```yaml
# API routes with special characters
/api/users/:id: getUserHandler
/api/posts: getPostsHandler
# Responsive breakpoints
mobile: @media (max-width: 768px)
tablet: @media (max-width: 1024px)
# Multi-line content
description:
This is a multi-line string
that preserves line breaks
exactly as written.
# Mixed data types
server:
host: localhost
port: 8080
debug: true
started: 2024-01-15T10:30:00Z
description:
```
--------------------------------
### Nuekit CLI: Project Commands
Source: https://context7.com/nuejs/nue/llms.txt
The Nuekit CLI offers unified commands for serving, building, and managing Nue projects. It supports features like instant startup, zero configuration, hot reload, production builds, previewing, selective file builds, verbose output, cleaning, dry runs, and project creation from templates. It's the primary tool for project development and management within the Nue ecosystem.
```bash
# Start development server with hot reload
nue serve
nue # serve is the default command
# Build production site
nue build
# Preview production build locally
nue preview --port 8080
# Build specific file types only
nue build .md .css
# Build with verbose output and clean dist
nue build --verbose --clean
# Dry run to see what would be built
nue build --dry-run
# Create new project from template
nue create my-blog
nue create my-app ./projects/myapp
```
--------------------------------
### GET /users
Source: https://github.com/nuejs/nue/blob/master/packages/www/docs/server-api.md
Handles GET requests for the /users path. Returns a list of users.
```APIDOC
## GET /users
### Description
Handles GET requests for the /users path. Returns a list of users.
### Method
GET
### Endpoint
/users
### Parameters
#### Path Parameters
None
#### Query Parameters
None
#### Request Body
None
### Request Example
None
### Response
#### Success Response (200)
- **field1** (type) - Description of the field.
#### Response Example
```json
{
"field1": "value1"
}
```
```
--------------------------------
### GET /users/:id
Source: https://github.com/nuejs/nue/blob/master/packages/www/docs/server-api.md
Handles GET requests for a specific user by ID. Extracts the ID from the path parameters.
```APIDOC
## GET /users/:id
### Description
Handles GET requests for a specific user by ID. Extracts the ID from the path parameters.
### Method
GET
### Endpoint
/users/:id
### Parameters
#### Path Parameters
- **id** (string) - Required - The ID of the user to retrieve.
#### Query Parameters
None
#### Request Body
None
### Request Example
None
### Response
#### Success Response (200)
- **field1** (type) - Description of the field.
#### Response Example
```json
{
"field1": "value1"
}
```
```
--------------------------------
### Single-Page Application Routing with JavaScript
Source: https://github.com/nuejs/nue/blob/master/packages/www/docs/nuekit.md
Illustrates a basic Single-Page Application (SPA) structure using HTML. It includes navigation links and a main content area where components are mounted dynamically based on URL routing. The `state.on('route', ...)` handler listens for route changes and mounts the corresponding component into the `` element.
```html
```
--------------------------------
### Nue Project File Structure Setup
Source: https://github.com/nuejs/nue/blob/master/packages/www/docs/migration.md
Defines the recommended directory organization for a Nue project with separate layouts for different sections (docs, blog), content files, and core HTML components. This structure replaces complex Next.js routing with a simple, purpose-based file organization.
```text
.
├── layout.html
├── components.html
├── docs/
│ ├── layout.html
│ ├── getting-started.md
│ ├── api-reference.md
│ └── deployment.md
├── blog/
│ ├── layout.html
│ ├── first-post.md
│ ├── design-systems.md
│ └── web-standards.md
├── about.md
├── pricing.md
└── index.md
```
--------------------------------
### Configure SPA entry point and routing with state management
Source: https://github.com/nuejs/nue/blob/master/packages/www/docs/spa-development.md
Set up the index.html file with dynamic HTML (dhtml) to handle all application routes. The state setup captures URL parameters and enables autolink for SPA navigation without page reloads.
```html
```
--------------------------------
### Run Production Build Command
Source: https://github.com/nuejs/nue/blob/master/packages/www/docs/build-system.md
Initiates the production build process for the Nue project. This command optimizes assets, processes files, and generates the final output for deployment.
```bash
nue build
```
--------------------------------
### Serve Demo with In-Browser Compilation
Source: https://github.com/nuejs/nue/blob/master/packages/www/docs/nuedom.md
Command to run a local development server using Bun to test the demo with in-browser compilation. This requires the http protocol for module loading.
```bash
bun bin/serve
```
--------------------------------
### Nuemark Nested Blocks Example
Source: https://github.com/nuejs/nue/blob/master/packages/www/docs/nuemark-syntax.md
Illustrates how Nuemark blocks can be nested. This example shows a main feature block containing a nested grid block, demonstrating hierarchical content structuring capabilities.
```markdown
[.feature]
## Main Feature
Feature description
[.grid]
### Sub-feature A
Description A
### Sub-feature B
Description B
```
--------------------------------
### Nue CLI Build Options
Source: https://github.com/nuejs/nue/blob/master/packages/www/docs/cli.md
Explains specific options for the `nue build` command. These options allow fine-tuning the build process, such as performing a dry run to simulate the build, initializing necessary runtime files, or cleaning the output directory before building.
```bash
# Dry Run
nue build --dry-run # preview build process
# Initialize Runtime
nue build --init
# Clean Output
nue build --clean # remove .dist then build
```
--------------------------------
### Nue CLI Basic Usage
Source: https://github.com/nuejs/nue/blob/master/packages/www/docs/cli.md
Demonstrates the fundamental structure of Nue CLI commands, including the default `dev` command and options for specifying a port or building the site. It highlights the flexibility in command invocation.
```bash
nue [command] [options] [file_matches]
# Default command (dev)
nue # same as "nue dev"
nue --port 8080 # serve on port 8080 (default 4000)
# Build command
nue build # build production site
# Preview command
nue preview # preview built site
```
--------------------------------
### Install Nueglow as NPM Package - Bash
Source: https://github.com/nuejs/nue/blob/master/packages/www/docs/nueglow.md
Installs Nueglow as a standalone Node.js package for use outside the Nue ecosystem. This allows integration with custom site generators and existing projects.
```bash
bun install nueglow
```
--------------------------------
### Setting up URL Search Parameters Configuration
Source: https://github.com/nuejs/nue/blob/master/packages/www/docs/state-api.md
Shows how to configure properties to be stored in URL search parameters using `state.setup()` with the `query` option. Changes to these properties update the URL search.
```javascript
state.setup({
query: ['search', 'filter', 'page']
})
state.search = 'shoes' // URL: ?search=shoes
state.filter = 'active' // URL: ?search=shoes&filter=active
state.page = 2 // URL: ?search=shoes&filter=active&page=2
```
--------------------------------
### GET Route Handler with Parameters
Source: https://github.com/nuejs/nue/blob/master/packages/www/docs/server-api.md
Handle GET requests with static routes and dynamic route parameters. Extract parameters from URL paths using c.req.param() method. Useful for retrieving specific resources by ID or other identifiers.
```javascript
get('/users', async (c) => {
return c.json(users)
})
get('/users/:id', async (c) => {
const id = c.req.param('id')
const user = users.find(u => u.id == id)
return c.json(user)
})
```
--------------------------------
### Nue SPA Entry Point Configuration (index.html)
Source: https://github.com/nuejs/nue/blob/master/packages/www/docs/single-page-apps.md
Configures the main `index.html` file to act as the SPA entry point. It sets up client-side routing using `state.setup` with URL parameters and `autolink` for seamless navigation. The `state.on` listener dynamically mounts components based on the URL's `id` parameter.
```html
```
--------------------------------
### Nue In-Browser Compilation Example
Source: https://github.com/nuejs/nue/blob/master/packages/www/docs/nuedom.md
Illustrates how Nue can be compiled directly in the browser using a small compiler, eliminating the need for build tools like Babel or Webpack. This example shows a simple counter component that updates in real-time.
```html
Nue In-browser compilation
```
--------------------------------
### Nue.js Basic Template Example
Source: https://github.com/nuejs/nue/blob/master/packages/www/docs/template-data.md
A fundamental example of a Nue.js template showcasing how to access data from the template context, such as site name and a collection of blog posts. It uses Nue's template syntax (`{ variable }` and `{{ expression }}`) for interpolation and iteration (`:each`).
```html
```
--------------------------------
### Middleware with use()
Source: https://github.com/nuejs/nue/blob/master/packages/www/docs/server-api.md
Demonstrates adding middleware that runs before route handlers, using the `use` function.
```APIDOC
## Middleware with use()
### Description
Adds middleware that runs before route handlers.
### Method
Use (Nueserver specific)
### Endpoint
`/admin/*` (example pattern)
### Parameters
#### Path Parameters
None
#### Query Parameters
None
#### Request Body
None
### Request Example
```javascript
use('/admin/*', async (c, next) => {
const auth = c.req.header('authorization')
if (!auth) return c.json({ error: 'Unauthorized' }, 401)
await next()
})
```
### Response
#### Success Response (200)
- **field1** (type) - Description of the field.
#### Response Example
```json
{
"field1": "value1"
}
```
## Global Middleware
### Description
Applies middleware globally to all requests.
### Method
Use (Nueserver specific)
### Endpoint
N/A (Global)
### Parameters
#### Path Parameters
None
#### Query Parameters
None
#### Request Body
None
### Request Example
```javascript
use(async (c, next) => {
console.log(c.req.method, c.req.url)
await next()
})
```
### Response
#### Success Response (200)
- **field1** (type) - Description of the field.
#### Response Example
```json
{
"field1": "value1"
}
```
```
--------------------------------
### GET /api/users
Source: https://context7.com/nuejs/nue/llms.txt
Retrieves a list of all users from the database.
```APIDOC
## GET /api/users
### Description
Retrieves a list of all users from the database.
### Method
GET
### Endpoint
/api/users
### Parameters
#### Query Parameters
None
#### Request Body
None
### Request Example
```json
{}
```
### Response
#### Success Response (200)
- **users** (array) - An array of user objects.
#### Response Example
```json
[
{
"id": 1,
"name": "John Doe",
"email": "john.doe@example.com"
}
]
```
```
--------------------------------
### GET /api/search
Source: https://context7.com/nuejs/nue/llms.txt
Searches for resources based on query parameters.
```APIDOC
## GET /api/search
### Description
Searches for resources based on query parameters.
### Method
GET
### Endpoint
/api/search
### Parameters
#### Query Parameters
- **q** (string) - Required - The search query.
- **page** (number) - Optional - The page number for results (defaults to 1).
#### Request Body
None
### Request Example
```json
{}`
### Response
#### Success Response (200)
- **results** (array) - An array of search results.
- **page** (number) - The current page number.
#### Response Example
```json
{
"results": [
{ "id": 1, "name": "Result 1" },
{ "id": 2, "name": "Result 2" }
],
"page": 1
}
```
```
--------------------------------
### Markdown Content with Layout Blocks and Components
Source: https://github.com/nuejs/nue/blob/master/packages/www/docs/nuekit.md
Shows how to define content pages using Markdown with frontmatter for metadata and layout blocks for structuring content. The example demonstrates a 'hero' section with a heading and a button, and a 'features' section with headings. It utilizes design system classes for styling, enabling content creators to work independently.
```markdown
---
title: Getting Started
sections: [hero, features, testimonials]
---
[.hero]
# Transform your workflow
Build consistent interfaces without the complexity
[button "Get Started" href="/docs"]
[.features]
## Design System First
Central CSS controls all visual decisions
## Component Assembly
Mix and match prepared components
```
--------------------------------
### GET /api/users/:id
Source: https://context7.com/nuejs/nue/llms.txt
Retrieves a specific user by their ID.
```APIDOC
## GET /api/users/:id
### Description
Retrieves a specific user by their ID.
### Method
GET
### Endpoint
/api/users/:id
### Parameters
#### Path Parameters
- **id** (string) - Required - The ID of the user to retrieve.
#### Query Parameters
None
#### Request Body
None
### Request Example
```json
{}
```
### Response
#### Success Response (200)
- **user** (object) - The user object matching the provided ID.
#### Error Response (404)
- **error** (string) - 'Not found'
#### Response Example
```json
{
"id": 1,
"name": "John Doe",
"email": "john.doe@example.com"
}
```
```
--------------------------------
### Next.js Login Form Component Example (React/JSX)
Source: https://github.com/nuejs/nue/blob/master/packages/www/docs/migration.md
This React component demonstrates a Next.js approach to form handling, where business logic, styling, data fetching, validation, and rendering are mixed within a single file. It utilizes libraries like React Hook Form, Zod, and TanStack Query. The example highlights the monolithic nature of such components and the scattering of concerns like state management and event handling.
```jsx
import { useState, useEffect } from 'react'
import { useRouter } from 'next/navigation'
import { useMutation } from '@tanstack/react-query'
import { useForm } from 'react-hook-form'
import { zodResolver } from '@hookform/resolvers/zod'
import { z } from 'zod'
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'
import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
import { Label } from '@/components/ui/label'
import { Alert, AlertDescription } from '@/components/ui/alert'
import { Loader2 } from 'lucide-react'
import { cn } from '@/lib/utils'
// Validation schema mixed with UI component
const loginSchema = z.object({
email: z.string().email('Invalid email address'),
password: z.string().min(6, 'Password must be at least 6 characters')
})
type LoginFormData = z.infer
export default function LoginForm() {
// State management hooks scattered throughout component
const [isLoading, setIsLoading] = useState(false)
const [error, setError] = useState(null)
const router = useRouter()
// Form validation library integration
const { register, handleSubmit, formState: { errors } } = useForm({
resolver: zodResolver(loginSchema)
})
// Business logic embedded in component
const loginMutation = useMutation({
mutationFn: async (data: LoginFormData) => {
// API call logic mixed with component
const response = await fetch('/api/auth/login', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(data)
})
return response.json()
}
})
// Event handlers with side effects
const onSubmit = async (data: LoginFormData) => {
// Authentication logic inside UI component
await loginMutation.mutateAsync(data)
router.push('/app/')
}
// Styling through utility classes and pre-built components
return (
// Semantic HTML buried under framework abstractions
Sign in to your account
// etc...
)
}
```
--------------------------------
### Setting up Local Storage Configuration
Source: https://github.com/nuejs/nue/blob/master/packages/www/docs/state-api.md
Demonstrates configuring properties to be stored in `localStorage` using `state.setup()` with the `local` option. These properties persist permanently on the device.
```javascript
state.setup({
local: ['theme', 'language', 'settings']
})
state.theme = 'dark'
state.language = 'en'
```
--------------------------------
### Create Nue Blog Project
Source: https://github.com/nuejs/nue/blob/master/packages/www/docs/project-structure.md
Command to create a Nue project structured for a content-focused blog, including shared layouts and automatic post collections.
```bash
nue create blog
```