• This repository has been archived on 23/Mar/2023
  • Stars
    star
    500
  • Rank 87,423 (Top 2 %)
  • Language
    JavaScript
  • License
    Mozilla Public Li...
  • Created over 5 years ago
  • Updated over 1 year ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

A Next.js plugin that enables MDX pages, layouts, and front matter

Note This repository is no longer maintained or in-use at HashiCorp. As of March 2023, the repository is archived.

Next.js + MDX Enhanced

build status

Are you using Next.js with MDX and wanted layouts and front matter? That's exactly what this plugin will do for you! 🌟

⚠️ You probably should be using next-mdx-remote instead of this library. It is ~50% faster, more flexible with content storage, does not induce memory issues at scale, and fits much better with the way that data is intended to flow through next.js.

For example, if have a site that displays content (e.g. documentation) that looks like:

MyDocsApp
β”œβ”€ pages
β”‚  β”œ index.jsx
β”‚  β”” docs
β”‚    β”œ intro.mdx
β”‚    β”” advanced.mdx
β”œβ”€ layouts
β”‚  β”” docs-page.jsx
β”” next.config.js

And you want the following:

feature next-mdx-enhanced @next/mdx
MDX files render as a navigable page βœ… βœ…
MDX files render with a common layout βœ… ❌
An index page that contains a navigable link to each MDX βœ… ❌

Installation

Install the package:

$ npm install next-mdx-enhanced

Usage & Options

Open the next.config.js file and instantiate it as a Next.js plugin:

// next.config.js
const withMdxEnhanced = require('next-mdx-enhanced')

module.exports = withMdxEnhanced({
  layoutPath: 'layouts',
  defaultLayout: true,
  fileExtensions: ['mdx'],
  remarkPlugins: [],
  rehypePlugins: [],
  usesSrc: false,
  extendFrontMatter: {
    process: (mdxContent, frontMatter) => {},
    phase: 'prebuild|loader|both',
  },
  reExportDataFetching: false,
})(/* your normal nextjs config */)

layoutPath

string | optional | default: layouts

The directory used to resolve the page layout when layout key present in MDX front matter. Value is resolved relative to project root.

defaultLayout

boolean | optional

Set value to true to treat index.[extension] within layoutPath as the default layout for any .mdx file that a layout has not been specified for.

fileExtensions

array | optional | default: ['mdx']

Array of file extensions that should be processed as MDX pages.

remarkPlugins

array | optional

Array of remark plugins used to transform .mdx files.

rehypePlugins

array | optional

Array of rehype plugins used to transform .mdx files.

usesSrc

boolean | optional | default: checks for src/pages to set the flag

It dictates if next mdx enhanced should use the src/pages for looking for the pages' folder. Otherwise, it will use the pages in the top-level directory. Also, if not set, it automatically checks for the src/pages directories.

extendFrontMatter

object | optional

Property Type Description
process function A hook function whose return value will be appended to the processed front matter. This function is given access to the source .mdx content as the first parameter and the processed front matter as the second parameter.
phase string Used to specify when to run the process function. Eligible values are prebuild, loader, both. Defaults to both if not specified.

scan

object | optional

Object of scan objects containing the following parameters

Property Type Description
pattern RegEx A RegEx to use for scanning .mdx content, enables Layout customization
transform function(match: Array[]): any optional An optional callback function that transforms the result of the match operation. This function is passed an Array of any matching .mdx content that is returned by content.match(pattern) operation utilizing the pattern RegEx.

See "Scanning MDX Content" for more details.

onContent

function(mdxContent) | optional

This function runs on each build of an MDX page. All metadata and full text content are passed to this function as its only argument.

Useful for indexing your content for site search or any other purpose where you'd like to capture content on build.

reExportDataFetching

boolean | optional

If you export getStaticProps and/or getServerSideProps from your layout, and wish for those to be re-exported from each of your mdx pages, set this option to true.

Layouts

Each MDX file may define the name of layout within its front matter.

Given an MDX page named pages/docs/intro.mdx:

---
layout: 'docs-page'
title: 'Introduction'
---

Here's some *markdown* content!

This loads the content within the layout defined at:

MyDocsApp
...
└─ layouts
   β”” docs-page.jsx # SEE supported extensions below
...

The plugin's layoutPath option defaults to layouts.

The file extension of the template must be one of configured pageExtensions.

The template, defined in layouts/docs-page.jsx, looks like the following:

// This function must be named otherwise it disables Fast Refresh.
export default function DocsPage({ children, frontMatter }) {
  // React hooks, for example `useState` or `useEffect`, go here.
  return (
    <div>
      <h1>{frontMatter.title}</h1>
      {children}
    </div>
  )
}

The default export function receives the front matter object, frontMatter, as a parameter. This function returns a rendering function. The rendering function receives an object that contains the the page content as children that is destructured and reassigned to content.

Front Matter

The front matter can be imported into your index pages and your templates. This enables you to create index pages or provide navigation across all your pages.

Create an index page

Given an index page named pages/index.jsx:

MyDocsApp
β”œβ”€ pages
β”‚  β”œ index.jsx
β”‚  β”” docs
β”‚    β”œ intro.mdx
β”‚    β”” advanced.mdx
β”œβ”€ layouts
β”‚  β”” docs-page.jsx
β”” next.config.js

With the content:

import Link from 'next/link'
import { frontMatter as introData } from './docs/intro.mdx'
import { frontMatter as advancedData } from './docs/advanced.mdx'

export default function DocsPage() {
  const docsPages = [introData, advancedData]

  return (
    <>
      <h1>Docs Index</h1>
      <ul>
        {docsPages.map((page) => (
          <li key={page.__resourcePath}>
            <Link href={formatPath(page.__resourcePath)}>
              <a>{page.title}</a>
            </Link>
          </li>
        ))}
      </ul>
    </>
  )
}

function formatPath(p) {
  return p.replace(/\.mdx$/, '')
}

This creates an index page of all the MDX pages found within docs.

Let's examine the contents of the index page step-by-step:

import { frontMatter as introData } from './docs/intro.mdx'
import { frontMatter as advancedData } from './docs/advanced.mdx'

First, the index page imports the destructured and renamed front matter from each of the docs pages. The front matter contains the title and location.

Don't repeat yourself: As the number of MDX pages grows, importing each front matter creates more maintenance that can be relieved by babel-plugin-import-glob-array. This plugin would enable you to specify this replacement those two imports with this file glob pattern: import {frontMatter as docsPages} from './docs/*.mdx'

Let's examine the code that renders each link:

export default function DocsPage() {
  const docsPages = [introData, advancedData]

  return (
    <>
      <h1>Docs Index</h1>
      <ul>
        {docsPages.map((page) => (
          <li key={page.__resourcePath}>
            <Link href={formatPath(page.__resourcePath)}>
              <a>{page.title}</a>
            </Link>
          </li>
        ))}
      </ul>
    </>
  )
}

function formatPath(p) {
  return p.replace(/\.mdx$/, '')
}

The __resourcePath is a property that stores the relative path to the MDX file and is automatically included in the front matter. The helper function formatPath strips the file extension to create a well-formed path to give to the NextJS <Link> component.

Performance tip: A description or summary field could be added to the front matter to keep the import small while enabling the index page to give a preview of the content.

This same procedure can also be done for layout files.

Implementation note: This plugin injects a babel plugin that extracts the front matter to temporary files. This removes the circular dependency created when a template imports a MDX page that imports that same template.

Scanning MDX Content

Sample next.config.js entry:

// in next.config.js
withMdxEnhanced({
  scan: [
    {
      someImportantKey: {
        pattern: /<SomeComponent.*name=['"](.*)['"].*\/>/,
        transform: (arr) => arr[1], // Optionally get a specific value back via a function;
        // if `transform` is omitted, any and all matches will be returned in an array
      },
    },
  ],
})

If an MDX page uses <SomeComponent />

---
layout: 'docs-page'
title: 'Advanced Docs'
---

import SomeComponent from '../../components/SomeComponent'

This is some _really_ **advanced** docs content!

<SomeComponent name="Find this text" />

This will produce an array of matches returned to your layout by the plugin.

__scans: {
  someImportantKey: ['Find this text']
}

Consume these values in the layout with the __scans key that is passed in attached to the front matter data.

export default function layoutWrapper(frontMatter) {
  const __scans = frontMatter.__scans
  return function Layout({ children }) {
    return (
   <>
    {/*..begin Layout..*/}
        {__scans.someImportantKey && (
          <h1>{__scans.someImportantKey}</h1> // returns <h1>Find this text</h1>
        )}
    {/*..end Layout..*/}
  </>

For more reference and an example use case please see the /scan-mdx-content/ test.

More Repositories

1

terraform

Terraform enables you to safely and predictably create, change, and improve infrastructure. It is a source-available tool that codifies APIs into declarative configuration files that can be shared amongst team members, treated as code, edited, reviewed, and versioned.
Go
42,052
star
2

vault

A tool for secrets management, encryption as a service, and privileged access management
Go
30,663
star
3

consul

Consul is a distributed, highly available, and data center aware solution to connect and configure applications across dynamic, distributed infrastructure.
Go
28,206
star
4

vagrant

Vagrant is a tool for building and distributing development environments.
Ruby
26,132
star
5

packer

Packer is a tool for creating identical machine images for multiple platforms from a single source configuration.
Go
15,018
star
6

nomad

Nomad is an easy-to-use, flexible, and performant workload orchestrator that can deploy a mix of microservice, batch, containerized, and non-containerized applications. Nomad is easy to operate and scale and has native Consul and Vault integrations.
Go
14,741
star
7

terraform-provider-aws

The AWS Provider enables Terraform to manage AWS resources.
Go
9,711
star
8

raft

Golang implementation of the Raft consensus protocol
Go
7,383
star
9

serf

Service orchestration and management tool.
Go
5,692
star
10

hcl

HCL is the HashiCorp configuration language.
Go
5,225
star
11

go-plugin

Golang plugin system over RPC.
Go
4,874
star
12

terraform-cdk

Define infrastructure resources using programming constructs and provision them using HashiCorp Terraform
TypeScript
4,801
star
13

waypoint

A tool to build, deploy, and release any application on any platform.
Go
4,789
star
14

consul-template

Template rendering, notifier, and supervisor for @HashiCorp Consul and Vault data.
Go
4,750
star
15

terraform-provider-azurerm

Terraform provider for Azure Resource Manager
Go
4,498
star
16

otto

Development and deployment made easy.
HTML
4,282
star
17

golang-lru

Golang LRU cache
Go
4,221
star
18

boundary

Boundary enables identity-based access management for dynamic infrastructure.
Go
3,829
star
19

memberlist

Golang package for gossip based membership and failure detection
Go
3,303
star
20

go-memdb

Golang in-memory database built on immutable radix trees
Go
2,937
star
21

next-mdx-remote

Load mdx content from anywhere through getStaticProps in next.js
TypeScript
2,405
star
22

terraform-provider-google

Terraform Provider for Google Cloud Platform
Go
2,267
star
23

go-multierror

A Go (golang) package for representing a list of errors as a single error.
Go
2,029
star
24

yamux

Golang connection multiplexing library
Go
2,003
star
25

envconsul

Launch a subprocess with environment variables using data from @HashiCorp Consul and Vault.
Go
1,967
star
26

go-retryablehttp

Retryable HTTP client in Go
Go
1,702
star
27

terraform-provider-kubernetes

Terraform Kubernetes provider
Go
1,571
star
28

go-getter

Package for downloading things from a string URL using a variety of protocols.
Go
1,541
star
29

best-practices

HCL
1,490
star
30

go-version

A Go (golang) library for parsing and verifying versions and version constraints.
Go
1,459
star
31

go-metrics

A Golang library for exporting performance and runtime metrics to external metrics systems (i.e. statsite, statsd)
Go
1,431
star
32

terraform-guides

Example usage of HashiCorp Terraform
HCL
1,324
star
33

setup-terraform

Sets up Terraform CLI in your GitHub Actions workflow.
JavaScript
1,303
star
34

mdns

Simple mDNS client/server library in Golang
Go
1,020
star
35

terraform-provider-helm

Terraform Helm provider
Go
990
star
36

vault-guides

Example usage of HashiCorp Vault secrets management
Shell
990
star
37

go-immutable-radix

An immutable radix tree implementation in Golang
Go
926
star
38

vault-helm

Helm chart to install Vault and other associated components.
Shell
904
star
39

terraform-ls

Terraform Language Server
Go
896
star
40

vscode-terraform

HashiCorp Terraform VSCode extension
TypeScript
870
star
41

levant

An open source templating and deployment tool for HashiCorp Nomad jobs
Go
825
star
42

vault-k8s

First-class support for Vault and Kubernetes.
Go
697
star
43

consul-k8s

First-class support for Consul Service Mesh on Kubernetes
Go
665
star
44

terraform-aws-vault

A Terraform Module for how to run Vault on AWS using Terraform and Packer
HCL
654
star
45

terraform-exec

Terraform CLI commands via Go.
Go
652
star
46

terraform-github-actions

Terraform GitHub Actions
Shell
624
star
47

terraform-provider-vsphere

Terraform Provider for VMware vSphere
Go
610
star
48

raft-boltdb

Raft backend implementation using BoltDB
Go
585
star
49

nextjs-bundle-analysis

A github action that provides detailed bundle analysis on PRs for next.js apps
JavaScript
562
star
50

go-discover

Discover nodes in cloud environments
Go
556
star
51

consul-replicate

Consul cross-DC KV replication daemon.
Go
504
star
52

terraform-provider-kubernetes-alpha

A Terraform provider for Kubernetes that uses dynamic resource types and server-side apply. Supports all Kubernetes resources.
Go
493
star
53

docker-vault

Official Docker images for Vault
Shell
492
star
54

terraform-k8s

Terraform Cloud Operator for Kubernetes
Go
454
star
55

vault-secrets-operator

The Vault Secrets Operator (VSO) allows Pods to consume Vault secrets natively from Kubernetes Secrets.
Go
450
star
56

puppet-bootstrap

A collection of single-file scripts to bootstrap your machines with Puppet.
Shell
444
star
57

cap

A collection of authentication Go packages related to OIDC, JWKs, Distributed Claims, LDAP
Go
436
star
58

terraform-provider-vault

Terraform Vault provider
Go
431
star
59

damon

A terminal UI (TUI) for HashiCorp Nomad
Go
427
star
60

nomad-autoscaler

Nomad Autoscaler brings autoscaling to your Nomad workloads.
Go
424
star
61

consul-helm

Helm chart to install Consul and other associated components.
Shell
422
star
62

terraform-provider-azuread

Terraform provider for Azure Active Directory
Go
419
star
63

vault-ssh-helper

Vault SSH Agent is used to enable one time keys and passwords
Go
404
star
64

terraform-provider-scaffolding

Quick start repository for creating a Terraform provider
Go
402
star
65

terraform-aws-consul

A Terraform Module for how to run Consul on AWS using Terraform and Packer
HCL
399
star
66

docker-consul

Official Docker images for Consul.
Dockerfile
399
star
67

hil

HIL is a small embedded language for string interpolations.
Go
392
star
68

vault-action

A GitHub Action that simplifies using HashiCorp Vaultβ„’ secrets as build variables.
JavaScript
391
star
69

nomad-pack

Go
390
star
70

learn-terraform-provision-eks-cluster

HCL
389
star
71

terraform-plugin-sdk

Terraform Plugin SDK enables building plugins (providers) to manage any service providers or custom in-house solutions
Go
383
star
72

terraform-config-inspect

A helper library for shallow inspection of Terraform configurations
Go
380
star
73

hcl2

Former temporary home for experimental new version of HCL
Go
375
star
74

errwrap

Errwrap is a Go (golang) library for wrapping and querying errors.
Go
373
star
75

go-cleanhttp

Go
362
star
76

design-system

Helios Design System
TypeScript
358
star
77

logutils

Utilities for slightly better logging in Go (Golang).
Go
356
star
78

vault-ruby

The official Ruby client for HashiCorp's Vault
Ruby
336
star
79

vault-rails

A Rails plugin for easily integrating Vault secrets
Ruby
334
star
80

waypoint-examples

Example Apps that can be deployed with Waypoint
PHP
326
star
81

next-remote-watch

Decorated local server for next.js that enables reloads from remote data changes
JavaScript
325
star
82

go-hclog

A common logging package for HashiCorp tools
Go
311
star
83

vault-csi-provider

HashiCorp Vault Provider for Secret Store CSI Driver
Go
305
star
84

nomad-guides

Example usage of HashiCorp Nomad
HCL
281
star
85

consul-haproxy

Consul HAProxy connector for real-time configuration
Go
279
star
86

consul-esm

External service monitoring for Consul
Go
262
star
87

terraform-provider-google-beta

Terraform Provider for Google Cloud Platform (Beta)
Go
261
star
88

http-echo

A tiny go web server that echos what you start it with!
Makefile
257
star
89

terraform-aws-nomad

A Terraform Module for how to run Nomad on AWS using Terraform and Packer
HCL
253
star
90

faas-nomad

OpenFaaS plugin for Nomad
Go
252
star
91

go-sockaddr

IP Address/UNIX Socket convenience functions for Go
Go
250
star
92

terraform-provider-awscc

Terraform AWS Cloud Control provider
HCL
247
star
93

terraform-foundational-policies-library

Sentinel is a language and framework for policy built to be embedded in existing software to enable fine-grained, logic-based policy decisions. This repository contains a library of Sentinel policies, developed by HashiCorp, that can be consumed directly within the Terraform Cloud platform.
HCL
233
star
94

nomad-driver-podman

A nomad task driver plugin for sandboxing workloads in podman containers
Go
226
star
95

vagrant-vmware-desktop

Official provider for VMware desktop products: Fusion, Player, and Workstation.
Go
225
star
96

go-tfe

HCP Terraform/Enterprise API Client/SDK in Golang
Go
224
star
97

nomad-pack-community-registry

A repo for Packs written and maintained by Nomad community members
HCL
215
star
98

boundary-reference-architecture

Example reference architecture for a high availability Boundary deployment on AWS.
HCL
211
star
99

terraform-plugin-framework

A next-generation framework for building Terraform providers.
Go
204
star
100

vault-plugin-auth-kubernetes

Vault authentication plugin for Kubernetes Service Accounts
Go
192
star