front-matter vs gray-matter vs remark-frontmatter vs yaml-front-matter
Parsing Metadata in Markdown Files
front-mattergray-matterremark-frontmatteryaml-front-matterSimilar Packages:

Parsing Metadata in Markdown Files

These libraries extract configuration data — known as front-matter — from the top of text files, usually Markdown. They separate metadata like titles and dates from the main body content. This allows static site generators and documentation tools to manage page settings without mixing code and content. While they share a goal, they differ in supported formats, integration style, and maintenance status.

Npm Package Weekly Downloads Trend

3 Years

Github Stars Ranking

Stat Detail

Package
Downloads
Stars
Size
Issues
Publish
License
front-matter0695-326 years agoMIT
gray-matter04,441-735 years agoMIT
remark-frontmatter032021.2 kB03 years agoMIT
yaml-front-matter0194-215 years agoMIT

Parsing Metadata in Markdown: front-matter vs gray-matter vs remark-frontmatter vs yaml-front-matter

When building static sites or documentation systems, you often need to store metadata at the top of a file. This block — called front-matter — usually contains titles, dates, or layout settings. Four popular packages handle this task, but they serve different roles in a modern stack. Let's compare how they parse data, handle formats, and fit into your build process.

📦 Core Parsing API: String vs AST

The biggest difference lies in what these tools return. Most parse the string into a JavaScript object and separate the body text. One tool integrates deeply with Markdown compilers.

gray-matter returns an object with content and data properties. It is designed for direct use in Node.js scripts.

import matter from 'gray-matter';

const file = '---\ntitle: Hello\n---\nBody text';
const result = matter(file);

console.log(result.data); // { title: 'Hello' }
console.log(result.content); // 'Body text'

front-matter returns an object with attributes and body. It is a simpler, older API.

import fm from 'front-matter';

const file = '---\ntitle: Hello\n---\nBody text';
const result = fm(file);

console.log(result.attributes); // { title: 'Hello' }
console.log(result.body); // 'Body text'

yaml-front-matter returns a single object where metadata keys are mixed with a __content key for the body. This can be messy if you iterate over keys.

import yamlFront from 'yaml-front-matter';

const file = '---\ntitle: Hello\n---\nBody text';
const result = yamlFront.loadFront(file);

console.log(result.title); // 'Hello'
console.log(result.__content); // 'Body text'

remark-frontmatter does not return a simple object. It works as a plugin for the remark processor and parses front-matter into an Abstract Syntax Tree (AST) node.

import { remark } from 'remark';
import frontmatter from 'remark-frontmatter';

const file = '---\ntitle: Hello\n---\nBody text';

const ast = await remark().use(frontmatter).process(file);
// The AST now contains a 'yaml' node type for the front-matter
// You must visit the tree to extract data manually or use other plugins

🛠 Format Support: YAML vs JSON vs TOML

Not all metadata is written in YAML. Some projects prefer JSON for strict typing or TOML for configuration clarity. Support varies significantly.

gray-matter handles multiple formats automatically or via options. You can switch engines easily.

import matter from 'gray-matter';

// Auto-detects YAML, JSON, or TOML
const result = matter(file);

// Force JSON parsing
const jsonResult = matter(file, { engines: { json: require('json-parse-better-errors') } });

front-matter primarily focuses on YAML. Extending it to other formats requires custom regex or additional logic.

import fm from 'front-matter';

// Primarily designed for YAML delimiters ---
const result = fm(file);
// JSON support is not built-in by default

yaml-front-matter is strictly for YAML as the name implies. It will not parse JSON or TOML blocks without significant modification.

import yamlFront from 'yaml-front-matter';

// Only parses YAML between --- delimiters
const result = yamlFront.loadFront(file);

remark-frontmatter supports YAML and TOML depending on configuration, but it treats them as syntax nodes rather than parsed data objects by default.

import frontmatter from 'remark-frontmatter';

// Configure to support yaml and toml
remark().use(frontmatter, ['yaml', 'toml']);
// Data remains in AST until another plugin processes it

🔗 Ecosystem Integration: Standalone vs Pipeline

Where you run these tools matters. Some fit into build scripts, while others belong inside compilers.

gray-matter is ideal for build scripts, Gatsby source nodes, or Next.js static generation. It runs before Markdown compilation.

// In a build script
files.forEach(file => {
  const { data, content } = matter(file);
  createPage({ path: data.slug, component: template, context: data });
});

front-matter works similarly to gray-matter but is often found in older Express apps or legacy static generators.

// In a legacy server route
app.get('/post', (req, res) => {
  const { attributes } = fm(readFile());
  res.render('post', attributes);
});

yaml-front-matter is typically found in very old static site generators. It is rarely used in modern pipelines.

// In an older build task
const data = yamlFront.loadFront(content);
writeJson(data);

remark-frontmatter is essential for plugins that transform Markdown content itself. It allows you to modify the front-matter node within the tree.

// In a remark plugin
export default function myPlugin() {
  return (tree) => {
    // Find the yaml node and modify it directly in the AST
    visit(tree, 'yaml', (node) => { node.value = '...' });
  };
}

⚠️ Maintenance and Future Proofing

Choosing a library is also about trusting its future. Some packages are stable, while others are effectively frozen.

gray-matter is actively maintained and widely adopted in the Jamstack community. It receives updates for security and performance.

// Safe for long-term projects
import matter from 'gray-matter';

remark-frontmatter is part of the unified collective. It is stable and updated alongside the remark ecosystem.

// Safe for compiler tooling
import frontmatter from 'remark-frontmatter';

front-matter receives occasional updates but development has slowed. It is stable but not evolving.

// Use with caution in new projects
import fm from 'front-matter';

yaml-front-matter has not seen significant updates in years. It is considered legacy and should be replaced.

// Do not use in new projects
import yamlFront from 'yaml-front-matter';

📊 Summary: Key Differences

Featuregray-matterremark-frontmatterfront-matteryaml-front-matter
Primary UseString ParsingAST ProcessingString ParsingString Parsing
FormatsYAML, JSON, TOMLYAML, TOMLYAMLYAML
OutputObject + ContentAST NodeObject + BodyMixed Object
StatusActiveActiveStableLegacy

💡 The Big Picture

gray-matter is the default choice for most developers. It handles the heavy lifting of parsing strings into usable data with great flexibility. Use it for static site generation and build scripts.

remark-frontmatter is the specialist tool. Reach for it when you are writing plugins for Markdown compilers and need to manipulate the document structure directly.

front-matter and yaml-front-matter are legacy options. Only use them if you are maintaining old codebases. For anything new, gray-matter provides a safer and more powerful foundation.

How to Choose: front-matter vs gray-matter vs remark-frontmatter vs yaml-front-matter

  • front-matter:

    Choose front-matter if you are maintaining a legacy project that already depends on it. It offers a simple API for YAML parsing but lacks the format flexibility of newer tools. For new projects, prefer gray-matter for better long-term support and features.

  • gray-matter:

    Choose gray-matter for most general-purpose parsing needs in Node.js environments. It supports YAML, JSON, and TOML out of the box with a robust API. It is the industry standard for extracting metadata from strings before processing Markdown.

  • remark-frontmatter:

    Choose remark-frontmatter when building a custom Markdown processor using the unified or remark ecosystem. It parses front-matter into AST nodes rather than plain objects. This allows you to transform or validate metadata as part of a larger compilation pipeline.

  • yaml-front-matter:

    Avoid yaml-front-matter in new projects as it is largely considered legacy software. It is limited to YAML and has seen minimal updates compared to gray-matter. Migrate existing usages to gray-matter for better security and format support.

README for front-matter

front-matter

build coverage npm github

Sauce Test Status

Extract meta data (front-matter) from documents.

This modules does not do any IO (file loading or reading), only extracting and parsing front matter from strings.

This concept that was originally introduced to me through the jekyll blogging system and is pretty useful where you want to be able to easily add meta-data to content without the need for a database. YAML is extracted from the the top of a file between matching separators of "---" or "= yaml =". It will also extract YAML between a separator and "...".

Install

With npm do:

npm install front-matter

Example

So you have a file example.md:

---
title: Just hack'n
description: Nothing to see here
---

This is some text about some stuff that happened sometime ago

NOTE: As of front-matter@2.0.0 valid front matter is considered to have the starting separator on the first line.

Then you can do this:

var fs = require('fs')
  , fm = require('front-matter')

fs.readFile('./example.md', 'utf8', function(err, data){
  if (err) throw err

  var content = fm(data)

  console.log(content)
})

And end up with an object like this:

{
    attributes: {
        title: 'Just hack\'n',
        description: 'Nothing to see here'
    },
    body: 'This is some text about some stuff that happened sometime ago',
    bodyBegin: 6,
    frontmatter: 'title: Just hack\'n\ndescription: Nothing to see here'
}

Methods

var fm = require('front-matter')

fm(string, { allowUnsafe: false })

Return a content object with two properties:

  • content.attributes contains the extracted yaml attributes in json form
  • content.body contains the string contents below the yaml separators
  • content.bodyBegin contains the line number the body contents begins at
  • content.frontmatter contains the original yaml string contents

NOTE: By default fm() uses ys-yaml's safeLoad unless you set allowUnsafe in the options object to true.

fm.test(string)

Check if a string contains a front matter header of "---" or "= yaml =". Primarily used internally but is useful outside of the module.

Returns true or false

    fm.test(string) #=> true || false

Contributing

front-matter is an OPEN Source Project so please help out by reporting bugs or forking and opening pull requests when possible.

standard

All code is linted/formatted using standard style, any non-conforming code can be automatically formatted using the the fmt make task: make fmt.

Maintainers

Contributors

This module is awesome because of all the folks who submitted pull requests:

CHANGELOG

3.0.0

  • CI only tests Node versions >= v6 (drops v4, and v5)

LICENSE (MIT)

Copyright (c) Jason Campbell ("Author")

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.