Docusaurus

This guide instructs you on how to integrate Netlify CMS with Docusaurus.

Before you begin

  • Sign up for GitHub and Netlify.
  • Download Node.js version 14 or above.
  • Install the GitHub CLI.
  • Install and authenticate the Netlify CLI.

Create a new Docusaurus project

# 1. Use Docusaurus to create a site scaffold.
npx create-docusaurus@latest my-website classic

# 2. Run the development server.
cd my-website
npm run start

A browser window opens at http://localhost:3000.

The development server now serves your website at http://localhost:3000. As you edit the source files in /my-website/, you can visit http://localhost:3000 to preview your changes.

Push your project to GitHub

Netlify CMS requires a backend to store content. Netlify CMS supports using Git hosts, like GitHub or GitLab, as backends. This guide uses GitHub.

# 1. Initialize your local Git repository.  
git init

# 2. Rename your initial branch to match GitHub.
git branch -m main

# 3. Stage all your local files to your repository.
git add . 

# 4. Commit your staged changes.
git commit -m 'Initial commit'

# 5. Create a remote repository on GitHub using the GitHub CLI.
gh repo create my-website

Don’t add a license or a .gitignore. Do add an “origin” git remote.

# 6. Update your remote repository with your staged changes. 
git push -u origin main

Publish your project using Netlify CLI

  1. Connect Netlify CLI to your GitHub repository.
    netlify init
  2. Choose Create & configure a new site.
  3. Choose your team and site name.
  4. Choose yarn build for your build command.
  5. Choose build for your deployment directory.

Choose the default option for everything else.

Your website is now deployed. Netlify provides you with a randomly generated domain name. Run netlify open --site to view your deployed site.

Add Netlify CMS to your project

Before you begin

  1. Remove all existing posts from /blog.
    rm -rf ./blog/*
  2. Create a new blog post post titled 2021-11-15-first-blog-post.md.
    touch ./blog/2021-11-15-first-blog-post.md
  3. Edit 2021-11-15-first-blog-post.md to look like this:
    ---
    title: First Blog Post
    slug: first-blog-post
    tags:
      - foo
      - bar
    authors:
      - name: Garrison McMullen
        title: Instruction Writer
        url: https://github.com/garrison0
        image_url: https://avatars.githubusercontent.com/u/4089393?v=4
    ---
    Lorem ipsum dolor sit amet, consectetur adipiscing elit. Pellentesque elementum dignissim ultricies. Fusce rhoncus ipsum tempor eros aliquam consequat.

Procedure

  1. Create an admin directory inside static.
    cd static
    mkdir admin
  2. In the admin directory, create a config.yml file and an index.html file.
    cd admin
    touch config.yml
    touch index.html
  3. Edit index.html to look like this:
    <!doctype html>
    <html>
    <head>
      <meta charset="utf-8" />
      <meta name="viewport" content="width=device-width, initial-scale=1.0" />
      <title>Content Manager</title>
    </head>
    <body>
      <!-- Include the script that builds the page and powers Netlify CMS -->
      <script src="https://unpkg.com/netlify-cms@^2.0.0/dist/netlify-cms.js"></script>
    </body>
    </html>

    index.html displays the Netlify CMS admin interface. You’ll use the admin interface to edit your blog posts.

  4. Edit config.yml to look like this:
    backend:
      name: github
      branch: main 
      repo: <your-github>/my-website
    
    # These lines should *not* be indented
    media_folder: "static/img" # Media files will be stored in the repo under static/images/uploads
    public_folder: "/img/" # The src attribute for uploaded media will begin with /images/uploads
    
    collections:
    - name: blog
      label: "blog"
      folder: blog
      identifier_field: title
      extension: md
      widget: "list"
      create: true
      slug: "{{year}}-{{month}}-{{day}}-{{slug}}" # Filename template, e.g., YYYY-MM-DD-title.md
      fields:
        - { name: title, label: Title, widget: string }
        - { name: body, label: Body, widget: markdown }
        - { name: slug, label: Slug, widget: string }
        - label: "Tags"
          name: "tags"
          widget: "list"
        - label: "Authors"
          name: "authors" 
          widget: "list"
          fields:
            - { name: name, label: Name, widget: string }
            - { name: title, label: Title, widget: string } 
            - { name: url, label: URL, widget: string } 
            - { name: imageUrl, label: ImageURL, widget: string } 

    config.yml specifies what kind of content your blog posts have. The content specification enables Netlify CMS to edit existing posts and create new ones with the same format. To learn more, read about Netlify CMS’ Configuration options.

  5. Visit localhost:3000/adminYou can now view and edit 2021-11-15-first-blog-post.md through the admin interface. You can also create new blog posts.Warning: Any changes you publish through the admin interface will only effect your remote GitHub repository. To retrieve these changes locally, git pull from your local repository.
  6. Commit and push your new changes to your remote repository.
    git add . 
    git commit -m "Add Netlify CMS"
    git push

    Netlify builds and deploys your new changes.

Add GitHub as an authentication provider

Before you can access /admin/ through your Netlify domain, you need to set up an authentication provider. The authentication provider allows Netlify CMS to determine whether users have read and write access to /admin/. This guide uses GitHub credentials for authentication.

Configure GitHub

  1. Create a new GitHub OAuth application.
  2. Enter your Netlify domain as the Homepage URL.
  3. Enter https://api.netlify.com/auth/done as the Authorization callback URL.
  4. Click Register application.
  5. Click Generate a new client secret.
  6. Copy the provided client secret and client ID.

Configure Netlify

  1. On Netlify, under Site Settings > Access control > OAuth > Authentication Providers, click Install provider.
  2. Enter your client secret and client ID from GitHub.
  3. Click Install.

🎉 All done! Now you can access the admin interface through your Netlify URL.

Azure Backend

For repositories stored on Azure, the azure backend allows CMS users to log in directly with their Azure account. Note that all users must have write access to your content repository for this to work.

In order to get Netlify-CMS working with Azure DevOps, you need a Tenant Id and an Application Id.

  1. If you do not have an Azure account, create one here and make sure to have a credit card linked to the account.
  2. If you do not have an Azure Active Directory Tenant Id, set one up here.
  3. Register an application with Azure AD. Configure it as a Single tenant Web application and add a redirect URI (e.g. http://localhost:8080/)
  4. Add the Azure DevOps->user_impersonation permission for the created application.
  5. Grant admin consent for the application.
  6. Under Authentication->Implicit grant enable Access tokens for the application and click Save.
  7. Verify your Azure DevOps organization is connected to the same directory as your tenant under: https://dev.azure.com/<organization>/_settings/organizationAad
  8. Add the following lines to your Netlify CMS config.yml file:
backend:
  name: azure
  repo: organization/project/repo # replace with actual path
  tenant_id: tenantId # replace with your tenantId
  app_id: appId # replace with your appId

Limitations

  1. Pagination is not supported so some endpoints might return missing data
  2. Nested collection are partially supported as Azure doesn’t allow renaming and editing in a single operation.

Nuxt

This guide will walk you through how to integrate Netlify CMS with Nuxt.

Starting With create-nuxt-app

Follow the instructions on the Nuxt documentation for creating a new project, or run:

npx create-nuxt-app <name-of-your-new-project>
cd <name-of-your-new-project>
npm run dev

Setting Up Netlify CMS

Add the Netlify CMS files to Nuxt

In the static/ directory, create a new directory admin/. Inside that directory you’ll create two files, your index.html and a config.yml. Per the Netlify CMS documentation, we’ll set the content of static/admin/index.html to the following:

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Content Manager</title>
    <!-- Include the script that enables Netlify Identity on this page. -->
    <script src="https://identity.netlify.com/v1/netlify-identity-widget.js"></script>
  </head>
  <body>
    <!-- Include the script that builds the page and powers Netlify CMS -->
    <script src="https://unpkg.com/netlify-cms@^2.0.0/dist/netlify-cms.js"></script>
  </body>
</html>

For your static/admin/config.yml file, you can put in a basic starter config:

backend:
  name: git-gateway
  branch: main # Branch to update (optional; defaults to master)

media_folder: static/img
public_folder: /img

collections:
  - name: 'blog'
    label: 'Blog'
    folder: 'content/blog'
    format: 'frontmatter'
    create: true
    slug: '{{year}}-{{month}}-{{day}}-{{slug}}'
    editor:
      preview: false
    fields:
      - { label: 'Title', name: 'title', widget: 'string' }
      - { label: 'Publish Date', name: 'date', widget: 'datetime' }
      - { label: 'Description', name: 'description', widget: 'string' }
      - { label: 'Body', name: 'body', widget: 'markdown' }

You can build whatever collections and content modeling you want. The important thing to note is the format: 'frontmatter' value on each collection. This is important for consuming content in Nuxt with the nuxt/content module.

Add the content/ directory to Nuxt

In your root directory, you can create a new directory content/. As you might guess, this is where our content will live. Your filesystem should look about like this, so far:

root/
├ content/
├ components/
├ layouts/
├ middleware/
├ pages/
├ plugins/
├ static/
│  └ admin/
│     ├ index.html
│     └ config.yml
├ store/
â”” // .editorconfig, .gitignore, nuxt.config.js, etc...

Pushing to GitHub

It’s now time to commit your changes and push to GitHub. create-nuxt-app initializes Git automatically for you, so you only need to do:

git add .
git commit -m "Initial Commit"
git remote add origin https://github.com/YOUR_USERNAME/NEW_REPO_NAME.git
git push -u origin main

Deploying With Netlify

Now you can go ahead and deploy to Netlify. Go to your Netlify dashboard and click New site from Git. Select the repo you just created. Under Basic build settings, you can set the build command to npm run generate . Set the publish directory to dist. Click Deploy site to get the process going.

Authenticating with Netlify Identity

Add the Netlify Identity Widget

You’ve already added the Netlify Identity widget to our admin/index.html. The next thing to do is add the Netlify Identity widget to our site’s index page. In pages/index.vue, we can add the following to the page <script> tag:

export default {
  head() {
    return {
      script: [{ src: 'https://identity.netlify.com/v1/netlify-identity-widget.js' }],
    };
  },
};

Once you’ve added this, make sure to push your changes to GitHub!

More on adding <script> tags to <head> here.

Enable Identity & Git Gateway in Netlify

Back in your Netlify dashboard:

  1. Go to Settings > Identity, and select Enable Identity service.
  2. Once enabled, select Settings and usage, and scroll down to Registration preferences. You can set this to either Open or Invite only, but usually Invite only is your best bet for a personal site.
  3. If you don’t want to create an account, or would like to use an external provider such as GitHub or Google, you can enable those services under External providers.
  4. Scroll down to Services and click Enable Git Gateway.

Accessing the CMS Once you’ve reached this point, you should be able to access the CMS in your browser at http://localhost:3000/admin. You’ll be prompted to add the URL of your Netlify site. Once you’ve added that URL, you can log in with an Identity account or with one of the External Providers you enabled in step 3 above. For the sake of this tutorial, you can create a blog post in the CMS, and publish it! Once you git pull in your project, the blog post will show up in the project at content/blog/<slugified-blog-post-title>.md.

Using nuxt/content

Netlify CMS and nuxt/content module click together and complement each other to give you best authoring experience and developer experience respectively.

Adding nuxt/content dependency

yarn add @nuxt/content
or
npm i @nuxt/content

Then, add @nuxt/content to the modules section of nuxt.config.js:

{
  modules: [
    '@nuxt/content'
  ],
  content: {
    // Options
  }
}

By adding nuxt content module you get $content injected into your whole app which you can use to fetch content from your content folder using simple fetch api or nuxt asyncData option.
This also gives a <nuxt-content> component which helps you display markdown content with ease and also gives option of live editing in dev mode.

Example Blog Post List

nuxt/content module gives us $content which we can use to fetch the list of blog posts in content/blog directory.

<template>
  <div>
    <li v-for="post of posts" :key="post.slug">
      <NuxtLink :to="post.slug">{{ post.title }}</NuxtLink>
    </li>
  </div>
</template>

<script>
export default {
   async asyncData({ $content }) {
    const posts = await $content("blog").fetch();

    return {
      posts,
    };
  },
};
</script>

Example Blog Post

To generate blog posts create a _slug.vue file in the pages folder. By using $content you would get a json which you can use to display. But if you are using markdown to write and store your posts you can use <nuxt-content> module which gives you option to edit content on page in dev mode and many more features.

<template>
  <div>
    <h2>{{ post.title }}</h2>
    <nuxt-content :document="post" />
  </div>
</template>

<script>
export default {
  async asyncData({ $content, params, error }) {
    let post;
    try {
      post = await $content("blog", params.slug).fetch();
      // OR const article = await $content(`articles/${params.slug}`).fetch()
    } catch (e) {
      error({ message: "Blog Post not found" });
    }

    return {
      post,
    };
  },
};
</script>

Generating pages with the generate property

Since Nuxt 2.13+, nuxt export has a crawler feature integrated which will crawl all your links and generate your routes based on those links. Therefore you do not need to do anything in order for your dynamic routes to be crawled. i.e, if you are on version of nuxt above 2.14 add target as static in nuxt.config.js and use nuxt generate to build your static site.

// nuxt.config.js
target: 'static'

If you are using nuxt version below 2.14 you have to use generate option in nuxt/content module to generate pages

//nuxt.config.js
export default {
  modules: [,
    '@nuxt/content'
  ],
  generate: {
    async routes () {
      const { $content } = require('@nuxt/content')
      const files = await $content().only(['path']).fetch()

      return files.map(file => file.path === '/index' ? '/' : file.path)
    }
  }
}

To render your site as a static site, you’ll need to create or update the generate property in nuxt.config.js to create dynamic routes and provide their content as a payload. In generate, make your routes entry a function:

export default {
  generate: {
    routes: function() {
      const fs = require('fs');
      const path = require('path');
      return fs.readdirSync('./content/blog').map(file => {
        return {
          route: `/blog/${path.parse(file).name}`, // Return the slug
          payload: require(`./content/blog/${file}`),
        };
      });
    },
  },
};

To see the generated site, navigate to name-of-your-website.netlify.app/blog.

Git Gateway Backend

Git Gateway is a Netlify open source project that allows you to add editors to your site CMS without giving them direct write access to your GitHub or GitLab repository. (For Bitbucket repositories, use the Bitbucket backend instead.)

Git Gateway with Netlify

The Netlify Identity service can handle the authentication and provides a simple interface for user management. The Netlify CMS featured templates are working examples of this backend.

To use it in your own project stored on GitHub or GitLab, follow these steps:

  1. Head over to the Netlify Identity docs and follow the steps to get started.
  2. Add the following lines to your Netlify CMS config.yml file:
backend:
  name: git-gateway

Reconnect after Changing Repository Permissions

If you change ownership on your repository, or convert a repository from public to private, you may need to reconnect Git Gateway with proper permissions. Find further instructions in the Netlify Git Gateway docs.

Git Gateway without Netlify

You can use Git Gateway without Netlify by setting up your own Git Gateway server and connecting it with your own instance of GoTrue (the open source microservice that powers Netlify Identity), or with any other identity service that can issue JSON Web Tokens (JWT).

To configure in Netlify CMS, use the same backend settings in your Netlify CMS config.yml file as described in Step 2 of the Git Gateway with Netlify Identity instructions above.

Authentication Providers

Authentication Providers

One challenge for frontend projects is handling authentication. OAuth2 is a widely accepted standard used by many services and APIs, but the OAuth authentication process requires a server to send a signed request to the OAuth server, signed with a secret that you can never expose to the client side of your application.

Netlify solves this problem by providing an integrated service that will sign the OAuth requests for you and give back an access token ready to use.

Netlify currently supports authentication with GitHub, GitLab, and Bitbucket.

#Enable OAuth for a Netlify site

While the below workflow is specifically for GitHub, the GitLab and Bitbucket workflows are similar.

Before you can use an authentication provider, you need to:

  1. register an API application with the OAuth provider
  2. configure credentials in the Netlify UI

#OAuth provider setup

You need to create an API application and make note of the Client ID and a Client Secret so that you can use them in your Netlify configuration.

  1. In GitHub, go to your account Settings and select Developer Settings, then OAuth Apps or use this shortcut.
  2. Select Register a new application.
  3. For the Authorization callback URL, enter https://web.archive.org/web/20220805155937/https://api.netlify.com/auth/done. The other fields can contain anything you want.
  4. On your new application’s GitHub overview page, make note of the Client ID.
  5. Generate a Client Secret and make note of it for later. You can’t access this secret again.

#Netlify UI settings

When you complete application registration with GitHub, you need to add the Client ID and Client Secret to your Netlify site:

  1. Go to Site settings > Access control > OAuth.
  2. Under Authentication Providers, select Install Provider.
  3. Select GitHub and enter the Client ID and Client Secret from earlier, then save.

#Site usage example

Once you’ve configured an authentication provider, you can use it to obtain an access token in your application.

You can preview the OAuth user experience in our demo.

Here’s an example of how to ask users to authenticate with GitHub and use the resulting token in your application’s calls to the GitHub API:

<!DOCTYPE html>
<html>
  <head>
    <title>GitHub Authentication Example</title>

    <!-- Make sure to include Netlify’s authentication library -->
    <!-- Also available from npm as netlify-auth-providers -->
    <script src="https://web.archive.org/web/20220805155937/https://unpkg.com/netlify-auth-providers"></script>
  </head>
  <body>
    <h1>GitHub Authentication Example:</h1>
    <p><a href="#" id="login">Authenticate</a></p>
    <p>Token: <span id="output-token">Not authenticated yet</span></p>
    <p>
      User emails:
      <span id="output-email">Not authenticated yet</span>
    </p>

    <script>
      const anchorTag = document.getElementById("login");
      const outputToken = document.getElementById("output-token");
      const outputEmail = document.getElementById("output-email");

      anchorTag.addEventListener("click", (event) => {
        event.preventDefault();

        const authenticator = new netlify.default({});

        authenticator.authenticate(
          // Set the OAuth provider and token scope
          // Provider can be "github", "gitlab", or "bitbucket"
          // The scopes available depend on your OAuth provider
          { provider: "github", scope: "user" },
          async function (error, data) {
            if (error) {
              outputToken.innerText =
                "Error Authenticating with GitHub: " + error;
            } else {
              outputToken.innerText =
                "Authenticated with GitHub. Access Token: " +
                data.token;
              outputEmail.innerText = await loadGitHubUserEmails(
                data.token
              );
            }
          }
        );
      });

      async function loadGitHubUserEmails(token) {
        return await fetch("https://web.archive.org/web/20220805155937/https://api.github.com/user/emails", {
          headers: {
            Accept: "application/vnd.github.v3+json",
            Authorization: `token ${token}`,
          },
        })
          .then((response) => response.json())
          .then((response) => JSON.stringify(response));
      }
    </script>
  </body>
</html> OAuth tokens are scoped to limit access. Each OAuth provider has different scopes you can use in your application. In the above GitHub example, the scope is set to user, which has read and write access to profile information. If you don’t provide a scope, OAuth providers usually apply the default scope to your token. Default scopes typically only have read access to public information. You can find a list of scopes for supported OAuth providers below: GitHub GitLab Bitbucket