Cheatsheets

n8n cheatsheets

Copy-paste-ready snippets for every-day n8n building.

For more depth, see the docs.n8n.io/code.

Expressions basics

n8n expressions are JavaScript wrapped in {{ }}, evaluated per item.

  • Current item field
    {{ $json.email }}
  • Nested field
    {{ $json.customer.address.city }}
  • Previous node's data
    {{ $node['HTTP Request'].json.id }}
  • First item of an array
    {{ $json.items[0].name }}
  • Lowercase & trim a string
    {{ $json.email.toLowerCase().trim() }}
  • Ternary / conditional
    {{ $json.age >= 18 ? 'adult' : 'minor' }}
  • Fallback / default value
    {{ $json.name || 'guest' }}
  • Optional chaining
    {{ $json.customer?.email ?? 'unknown' }}
  • Template literal / concatenation
    {{ `${$json.firstName} ${$json.lastName}` }}
  • JSON stringify a value
    {{ JSON.stringify($json) }}
  • Number formatting
    {{ $json.price.toFixed(2) }}
  • Environment variable
    {{ $env.MY_API_KEY }}

Built-in variables & methods

n8n exposes special $-prefixed variables inside expressions and the Code node.

  • Current item JSON
    $json

    Shorthand for $input.item.json inside expressions.

  • Data from a named node
    $node['Set'].json.total
  • All items from a node
    $('Set').all()
  • First/last item from a node
    $('Set').first().json
    $('Set').last().json
  • Current workflow metadata
    $workflow.id
    $workflow.name
  • Current execution metadata
    $execution.id
    $execution.mode
  • All input items (Code node)
    $input.all()
  • Current date/time
    $now
  • Today at midnight
    $today
  • Reference workflow static data
    $getWorkflowStaticData('global')
  • Item's own index/position
    $itemIndex
  • Run JMESPath query
    {{ $jmespath($json.items, '[?price > `10`].name') }}

Luxon date handling

n8n uses Luxon for date logic; $now and $today return Luxon DateTime objects.

  • Now as ISO string
    {{ $now.toISO() }}
  • Custom format
    {{ $now.toFormat('yyyy-MM-dd HH:mm') }}
  • Add/subtract time
    {{ $now.plus({ days: 7 }) }}
    {{ $now.minus({ hours: 3 }) }}
  • Difference between two dates
    {{ $json.dueDate.diff($now, 'days').days }}
  • Parse a string to DateTime
    {{ DateTime.fromISO($json.createdAt) }}
  • Convert timezone
    {{ $now.setZone('Asia/Riyadh').toISO() }}
  • Start/end of day
    {{ $now.startOf('day') }}
    {{ $now.endOf('day') }}
  • Weekday name
    {{ $now.toFormat('cccc') }}
  • Unix timestamp (seconds)
    {{ $now.toSeconds() }}
  • Compare two dates
    {{ $now > DateTime.fromISO($json.expiry) }}

Cron & Schedule Trigger

Use the Schedule Trigger node's cron expression field for custom intervals.

  • Every minute
    * * * * *
  • Every 5 minutes
    */5 * * * *
  • Every hour
    0 * * * *
  • Every 6 hours
    0 */6 * * *
  • Daily at 09:00
    0 9 * * *
  • Weekdays at 08:30
    30 8 * * 1-5
  • Every Sunday at midnight
    0 0 * * 0
  • First day of month
    0 0 1 * *
  • Twice a day (9am & 9pm)
    0 9,21 * * *
  • Every 15 seconds (Seconds mode)
    Trigger Interval: Seconds · Seconds Between Triggers: 15

HTTP Request, auth & pagination

The HTTP Request node covers most REST API integrations n8n doesn't have a dedicated node for.

  • Send JSON body (POST)
    Method: POST · Body Content Type: JSON
    Body: { "key": "{{$json.x}}" }
  • Bearer token auth
    Authentication: Header Auth
    Header: Authorization = Bearer {{$env.TOKEN}}
  • Basic auth
    Authentication: Basic Auth (username/password credential)
  • Query parameters
    Send Query Parameters: true
    page = {{$json.page}} · limit = 50
  • Offset-based pagination
    Pagination → Update a Parameter
    offset = {{$pageCount * 50}}
    Complete when: response body is empty
  • Cursor-based pagination
    Pagination → Response has more items
    Next cursor: {{$response.body.next_cursor}}
  • Retry on fail
    Settings → Retry On Fail: true
    Max Tries: 5 · Wait Between Tries: 2000ms
  • Custom timeout
    Options → Timeout: 10000
  • Batching / rate limiting
    Options → Batching → Batch Size: 5 · Interval: 1000ms
  • Ignore SSL issues (dev only)
    Options → Ignore SSL Issues: true

Error handling & retries

Combine node-level settings with a workflow-level Error Workflow for resilient automations.

  • Continue on fail
    Node → Settings → On Error: Continue
  • Continue using error output
    Node → Settings → On Error: Continue (using error output)
  • Assign a workflow error handler
    Workflow → Settings → Error Workflow: 'Global Alerts'
  • Read error details in the error workflow
    {{ $json.execution.error.message }}
  • Throw a custom error (Code node)
    if (!$json.email) {
      throw new Error('Missing email field');
    }
    return $input.all();
  • Stop and error node
    Stop And Error node → Error Message: 'Invalid payload'
  • Try/catch inside Code node
    try {
      return items.map(i => ({ json: JSON.parse(i.json.raw) }));
    } catch (e) {
      return [{ json: { error: e.message } }];
    }
  • Notify on failure via Slack
    Slack node in Error Workflow:
    Text: "❌ {{$json.workflow.name}} failed: {{$json.execution.error.message}}"

Code node JS snippets

The Code node can run once for all items or once per item — pick the right mode for your use case.

  • Return all items unchanged
    return $input.all();
  • Map/transform every item
    return $input.all().map(item => ({
      json: { ...item.json, fullName: `${item.json.first} ${item.json.last}` }
    }));
  • Filter items
    return $input.all().filter(item => item.json.active === true);
  • Deduplicate by field
    const seen = new Set();
    return $input.all().filter(item => {
      if (seen.has(item.json.email)) return false;
      seen.add(item.json.email);
      return true;
    });
  • Aggregate a sum
    const total = $input.all().reduce((sum, i) => sum + i.json.amount, 0);
    return [{ json: { total } }];
  • Group items by key
    const groups = {};
    for (const item of $input.all()) {
      const key = item.json.category;
      (groups[key] ??= []).push(item.json);
    }
    return Object.entries(groups).map(([category, items]) => ({ json: { category, items } }));
  • Flatten a nested array into items
    return $json.orders.map(order => ({ json: order }));
  • Call fetch inside Code node
    const res = await this.helpers.httpRequest({ url: 'https://api.example.com/data' });
    return [{ json: res }];
  • Access credentials in Code node
    const creds = await this.getCredentials('httpHeaderAuth');
    return [{ json: { hasToken: !!creds.value } }];

AI Agent / LangChain nodes

n8n's LangChain integration lets you build agents, RAG pipelines, and structured extraction visually.

  • Basic AI Agent setup
    Chat Trigger → AI Agent
      ├─ Chat Model: OpenAI/Anthropic
      ├─ Memory: Window Buffer Memory
      └─ Tools: HTTP Request Tool, Vector Store Tool
  • System prompt field
    AI Agent → Options → System Message:
    "You are a support agent for Acme. Be concise and always cite sources."
  • Add a custom tool from a workflow
    Tool: 'Call n8n Workflow Tool'
    Workflow: 'Lookup Order Status'
    Description: 'Looks up an order status by order ID'
  • Structured Output Parser schema
    {
      "type": "object",
      "properties": {
        "sentiment": { "type": "string" },
        "summary": { "type": "string" }
      }
    }
  • Simple RAG chain
    Vector Store (Qdrant) → Retrieve
      ↓
    Question & Answer Chain
      ↓ context + question
    Chat Model
  • Ingest documents into a vector store
    Default Data Loader → Text Splitter (Recursive)
      ↓
    Embeddings (OpenAI) → Vector Store (Insert mode)
  • Access agent output in next node
    {{ $json.output }}
  • Limit agent iterations
    AI Agent → Options → Max Iterations: 10
  • Use Simple Memory scoped per session
    Memory: Simple Memory
    Session ID: {{$json.sessionId}}

Data transformation & Item Lists

No-code alternatives to the Code node for common list/array operations.

  • Split items into batches
    Split In Batches node → Batch Size: 10
  • Sort items by a field
    Sort node → Type: Simple
    Field: createdAt · Order: Descending
  • Remove duplicate items
    Remove Duplicates node → Compare: Selected Fields → email
  • Limit number of items
    Limit node → Max Items: 50 · Keep: First Items
  • Aggregate items into one
    Aggregate node → Aggregate: All Item Data
    Destination Field Name: results
  • Summarize (sum/avg/count)
    Summarize node → Field: amount → Aggregation: Sum
  • Rename multiple fields
    Edit Fields (Set) node → Mode: Manual Mapping
    full_name = {{$json.name}} · email_addr = {{$json.email}}
  • Convert list of objects to CSV
    Convert to File node → File Format: CSV
  • Compare two datasets (Merge)
    Merge node → Mode: Combine → Match Fields
    Field to match: id

Full official reference: docs.n8n.io/code