DEV Community

楊東霖
楊東霖

Posted on • Originally published at devtoolkit.cc

How to Validate YAML in JavaScript and Node.js

Knowing how to validate YAML in JavaScript is essential for any developer working with configuration files, CI/CD pipelines, or data serialization. YAML is widely used in projects like Docker Compose, Kubernetes manifests, and GitHub Actions — and a single misplaced indent can break an entire deployment. This guide covers the two most popular npm packages for parsing and validating YAML in Node.js, common pitfalls to watch for, and practical schema validation techniques.

The Two Main Libraries: js-yaml vs yaml

Two packages dominate YAML parsing in the JavaScript ecosystem:

  • js-yaml — the long-standing, battle-tested choice with over 100 million weekly downloads
  • yaml — a newer, standards-compliant library with better error messages and TypeScript support

Both are excellent. js-yaml is the default choice for most legacy projects, while yaml is preferred for greenfield TypeScript projects or when you need round-trip editing (preserve comments and formatting).

Parsing and Validating with js-yaml

Install the package first:

npm install js-yaml
Enter fullscreen mode Exit fullscreen mode

Basic parsing and catching parse errors:

const yaml = require('js-yaml');
const fs = require('fs');

try {
  const doc = yaml.load(fs.readFileSync('config.yaml', 'utf8'));
  console.log(doc);
} catch (e) {
  if (e instanceof yaml.YAMLException) {
    console.error('YAML parse error:', e.message);
    console.error('Line:', e.mark?.line);
    console.error('Column:', e.mark?.column);
  }
}
Enter fullscreen mode Exit fullscreen mode

The yaml.load() function parses a single YAML document. For files containing multiple documents separated by ---, use yaml.loadAll():

const docs = yaml.loadAll(multiDocYamlString);
docs.forEach((doc, i) => {
  console.log(`Document ${i}:`, doc);
});
Enter fullscreen mode Exit fullscreen mode

Parsing and Validating with the yaml Package

npm install yaml
Enter fullscreen mode Exit fullscreen mode

The yaml package provides richer error information:

import { parse, parseDocument } from 'yaml';

// Simple parse — throws on invalid YAML
try {
  const result = parse(yamlString);
  console.log(result);
} catch (err) {
  console.error(err.message); // Detailed message with line/col
}

// parseDocument — collects warnings without throwing
const doc = parseDocument(yamlString);
if (doc.errors.length > 0) {
  doc.errors.forEach(err => console.error('Error:', err.message));
}
if (doc.warnings.length > 0) {
  doc.warnings.forEach(w => console.warn('Warning:', w.message));
}
const data = doc.toJS();
Enter fullscreen mode Exit fullscreen mode

Using parseDocument() is preferable when you want to report all errors at once rather than stopping at the first one.

Schema Validation with Zod (After Parsing)

YAML libraries only check syntactic correctness — they cannot tell you whether your parsed object has the right shape. Combine YAML parsing with a schema validator like Zod for full validation:

import { parse } from 'yaml';
import { z } from 'zod';

const ConfigSchema = z.object({
  server: z.object({
    host: z.string(),
    port: z.number().min(1).max(65535),
  }),
  database: z.object({
    url: z.string().url(),
    maxConnections: z.number().default(10),
  }),
  features: z.array(z.string()).optional(),
});

function validateConfig(yamlString) {
  let raw;
  try {
    raw = parse(yamlString);
  } catch (err) {
    throw new Error(`YAML syntax error: ${err.message}`);
  }

  const result = ConfigSchema.safeParse(raw);
  if (!result.success) {
    const issues = result.error.issues.map(
      i => `${i.path.join('.')}: ${i.message}`
    );
    throw new Error(`Config validation failed:\n${issues.join('\n')}`);
  }
  return result.data;
}
Enter fullscreen mode Exit fullscreen mode

This two-stage approach — parse first, then schema-validate — is the most robust pattern for configuration loading in production Node.js applications.

Common YAML Errors and How to Fix Them

1. Tab Characters Instead of Spaces

YAML does not allow tab characters for indentation. Always use spaces.

# WRONG — uses a tab
key:
    value: oops

# CORRECT — uses spaces
key:
  value: good
Enter fullscreen mode Exit fullscreen mode

2. Unquoted Special Characters

Characters like :, #, @, and

``` can break YAML when unquoted:


yaml
# WRONG
message: Hello: world

# CORRECT
message: "Hello: world"


Enter fullscreen mode Exit fullscreen mode

3. Inconsistent Indentation

All sibling keys at the same level must use the same indentation depth. Mixing 2-space and 4-space indentation within a file causes parse failures.

4. The Norway Problem (Boolean Coercion)

js-yaml in YAML 1.1 mode interprets NO, YES, ON, OFF as booleans. Country codes like NO (Norway) become false. Use yaml.load(str, { schema: yaml.JSON_SCHEMA }) or the newer yaml package (which defaults to YAML 1.2) to avoid this.


javascript
// Safe parsing — YAML 1.2 schema avoids boolean coercion
const doc = yaml.load(input, { schema: yaml.JSON_SCHEMA });


Enter fullscreen mode Exit fullscreen mode

Validating YAML in the Browser

Both js-yaml and yaml work in the browser. Bundle them with your frontend to validate YAML client-side before submission. For quick ad-hoc validation during development, the YAML to JSON converter tool instantly shows parse errors and converts valid YAML to JSON so you can inspect the structure.

Writing YAML Safely from JavaScript

To serialize a JavaScript object back to a YAML string:


javascript
// js-yaml
const yamlString = yaml.dump({
  server: { host: 'localhost', port: 3000 },
  features: ['auth', 'logging'],
});

// yaml package
import { stringify } from 'yaml';
const yamlString = stringify(myObject);


Enter fullscreen mode Exit fullscreen mode

Never build YAML strings by hand with template literals — always use a library to ensure correct escaping and indentation.

Summary

  • Use js-yaml for quick, familiar parsing in legacy or CommonJS projects
  • Use the yaml package for TypeScript, YAML 1.2 compliance, and better error messages
  • Always wrap parsing in try/catch and inspect YAMLException details
  • Add Zod or Joi schema validation after parsing to enforce structure
  • Prefer JSON_SCHEMA mode or the yaml package to avoid the Norway boolean problem

Want these tools available offline? The DevToolkit Bundle ($9 on Gumroad) packages 40+ developer tools into a single downloadable kit — no internet required.

Free Developer Tools

If you found this article helpful, check out DevToolkit — 40+ free browser-based developer tools with no signup required.

Popular tools: JSON Formatter · Regex Tester · JWT Decoder · Base64 Encoder

🛒 Get the DevToolkit Starter Kit on Gumroad — source code, deployment guide, and customization templates.

Top comments (0)