Authentication & Backends

Netlify CMS stores content in your GitHub, GitLab, or Bitbucket repository. In order for this to work, it must authenticate with your Git host. In most cases that requires a server. We have a few options for handling this.

Note: If you prefer to run your own authentication server, check out the section on external OAuth clients.

Note: Some static site generators have plugins for optimized integration with Netlify CMS, and starter templates may utilize these plugins. If you’re using a starter template, read the template documentation before proceeding, as their instructions may differ.

Git Gateway with Netlify Identity

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.) 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
      accept_roles: #optional - accepts all users if left out
        - admin
        - editor
  3. Optionally, you can assign roles to users in your Netlify dashboard, and then limit which roles can access the CMS by defining the accept_roles field as shown in the example above. Otherwise accept_roles can be left out, and all Netlify Identity users on your site have access.

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.

GitHub Backend

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

Because Github requires a server for authentication, Netlify facilitates basic GitHub authentication.

To enable basic GitHub authentication:

  1. Follow the authentication provider setup steps in the Netlify docs.
  2. Add the following lines to your Netlify CMS config.yml file:
    backend:
      name: github
      repo: owner-name/repo-name # Path to your GitHub repository

Specifying a status for deploy previews

The GitHub backend supports deploy preview links. Netlify CMS checks the context of a commit’s statuses and infers one that seems to represent a deploy preview. If you need to customize this behavior, you can specify which context to look for using preview_context:

```yaml
backend:
  name: github
  repo: my/repo
  preview_context: my-provider/deployment
```

The above configuration would look for the status who’s "context" is "my-provider/deployment".

GitLab Backend

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

The GitLab API allows for two types of OAuth2 flows:

  • Web Application Flow, which works much like the GitHub OAuth flow described above.
  • Implicit Grant, which operates without the need for an authentication server.

Web Application Flow with Netlify

When using GitLab’s Web Application Flow for authentication, you can use Netlify to handle the server-side authentication requests.

To enable it:

  1. Follow the GitLab docs to add your Netlify CMS instance as an OAuth application. For the Redirect URI, enter https://api.netlify.com/auth/done, and check the box for api scope.
  2. Follow the Netlify docs to add your new GitLab Application ID and Secret to your Netlify site dashboard.
  3. In your repository, add the following lines to your Netlify CMS config.yml file:
    backend:
      name: gitlab
      repo: owner-name/repo-name # Path to your GitLab repository

Client-Side Implicit Grant (GitLab)

With GitLab’s Implicit Grant, users can authenticate with GitLab directly from the client. To do this:

  1. Follow the GitLab docs to add your Netlify CMS instance as an OAuth application. For the Redirect URI, enter the address where you access Netlify CMS, for example, https://www.mysite.com/admin/. For scope, select api.
  2. GitLab gives you an Application ID. Copy this ID and enter it in your Netlify CMS config.yml file, along with the following settings:
    backend:
      name: gitlab
      repo: owner-name/repo-name # Path to your GitLab repository
      auth_type: implicit # Required for implicit grant
      app_id: your-app-id # Application ID from your GitLab settings

    You can also use Implicit Grant with a self-hosted GitLab instance. This requires adding api_root, base_url, and auth_endpoint fields:

    backend:
      name: gitlab
      repo: owner-name/repo-name # Path to your GitLab repository
      auth_type: implicit # Required for implicit grant
      app_id: your-app-id # Application ID from your GitLab settings
      api_root: https://my-hosted-gitlab-instance.com/api/v4
      base_url: https://my-hosted-gitlab-instance.com
      auth_endpoint: oauth/authorize

Note: In both cases, GitLab also provides you with a client secret. You should never store this in your repo or reveal it in the client.

Bitbucket Backend

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

To enable it:

  1. Follow the authentication provider setup steps in the Netlify docs.
  2. Add the following lines to your Netlify CMS config.yml file:
    backend:
      name: bitbucket
      repo: owner-name/repo-name # Path to your Bitbucket repository

Client-Side Implicit Grant (Bitbucket)

With Bitbucket’s Implicit Grant, users can authenticate with Bitbucket directly from the client. To do this:

  1. Follow the authentication provider setup steps in the Netlify docs, make sure you allow ‘Account/Read’ and ‘Repository/Write’.
  2. Bitbucket gives you a Key. Copy this Key and enter it in your Netlify CMD config.yml file, along with the following settings:
    backend:
      name: bitbucket
      repo: owner-name/repo-name
      branch: default
      auth_type: implicit
      app_id: # The Key from your Bitbucket settings

Warning: With Bitbucket implicit grant, the authentication is valid for 1 hour only. After that, the user has to login again, which can lead to data loss if the expiration occurs while content is being edited.

Test Repo Backend

You can use the test-repo backend to try out Netlify CMS without connecting to a Git repo. With this backend, you can write and publish content normally, but any changes will disapear when you reload the page. This backend powers the Netlify CMS demo site.

To enable this backend, add the following lines to your Netlify CMS config.yml file:

backend:
  name: test-repo

External OAuth Clients

If you would like to facilitate your own OAuth authentication rather than use Netlify’s service or implicit grant, you can use one of the community-maintained projects below. Feel free to submit a pull request if you’d like to add yours!

Author Supported Git hosts Language(s)/Platform(s) Link
@vencax GitHub, GitHub Enterprise Node.js Repo
@igk1972 GitHub, GitHub Enterprise Go Repo
@davidejones GitHub, GitHub Enterprise Python Repo
@marcelkornblum GitHub, GitHub Enterprise Google AppEngine with Python Repo
@marksteele GitHub, GitHub Enterprise Serverless Repo, Blog
@Herohtar GitHub, GitHub Enterprise Firebase Cloud Function Repo

Check each project’s documentation for instructions on how to configure it.

Options

Netlify CMS backends allow some additional fields for certain use cases. A full reference is below. Note that these are properties of the backend field, and should be nested under that field.

Field Default Description
repo none Required for github, gitlab, and bitbucket backends; ignored by git-gateway. Follows the pattern [org-or-username]/[repo-name].
accept_roles none git-gateway only. Limits CMS access to your defined array of user roles. Omitting this field gives access to all registered users.
branch master The branch where published content is stored. All CMS commits and PRs are made to this branch.
api_root https://api.github.com (GitHub), https://gitlab.com/api/v4 (GitLab), or https://api.bitbucket.org/2.0 (Bitbucket) The API endpoint. Only necessary in certain cases, like with GitHub Enterprise or self-hosted GitLab.
site_domain location.hostname (or cms.netlify.com when on localhost) Sets the site_id query param sent to the API endpoint. Non-Netlify auth setups will often need to set this for local development to work properly.
base_url https://api.netlify.com (GitHub, Bitbucket) or https://gitlab.com (GitLab) OAuth client hostname (just the base domain, no path). Required when using an external OAuth server or self-hosted GitLab.
auth_endpoint auth (GitHub, Bitbucket) or oauth/authorize (GitLab) Path to append to base_url for authentication requests. Optional.

Backends Overview

Overview

A backend is JavaScript code that allows Netlify CMS to communicate with a service that stores content – typically a Git host like GitHub or GitLab. It provides functions that Netlify CMS can use to do things like read and update files using API’s provided by the service.

Backend Configuration

Individual backends should provide their own configuration documentation, but there are some configuration options that are common to multiple backends. A full reference is below. Note that these are properties of the backend field, and should be nested under that field.

Field Default Description
repo none Required for github, gitlab, and bitbucket backends; ignored by git-gateway. Follows the pattern [org-or-username]/[repo-name].
branch master The branch where published content is stored. All CMS commits and PRs are made to this branch.
api_root https://api.github.com (GitHub), https://gitlab.com/api/v4 (GitLab), or https://api.bitbucket.org/2.0 (Bitbucket) The API endpoint. Only necessary in certain cases, like with GitHub Enterprise or self-hosted GitLab.
site_domain location.hostname (or cms.netlify.com when on localhost) Sets the site_id query param sent to the API endpoint. Non-Netlify auth setups will often need to set this for local development to work properly.
base_url https://api.netlify.com (GitHub, Bitbucket) or https://gitlab.com (GitLab) OAuth client hostname (just the base domain, no path). Required when using an external OAuth server or self-hosted GitLab.
auth_endpoint auth (GitHub, Bitbucket) or oauth/authorize (GitLab) Path to append to base_url for authentication requests. Optional.
cms_label_prefix netlify-cms/ Pull (or Merge) Requests label prefix when using editorial workflow. Optional.

Creating a New Backend

Anyone can write a backend, but we don’t yet have a finalized and documented API. If you would like to write your own backend for a service that does not have one currently, we recommend using the GitHub backend as a reference for API and best practices.

Take a test drive

You can easily try out Netlify CMS by running it on a pre-configured starter site. Our example in the intro is the Kaldi small business Hugo template. Use the deploy button below to build and deploy your own copy of the repository: Deploy to Netlify.

Authenticate with GitHub

When the deploy completes, you can see your site, but in order to use the CMS, you’ll need to set up authentication with GitHub.

First, register the site CMS as an authorized application with your GitHub account:

  1. Go to your account Settings page on GitHub, and click Oauth Applications under Developer Settings (or use this shortcut).
  2. Click Register a new application.
  3. For the Authorization callback URL, enter https://api.netlify.com/auth/done. The other fields can contain anything you want.

GitHub Oauth Application setup example

When you complete the registration, you’ll be given a Client ID and a Client Secret for the app. You’ll need to add these to your Netlify project:

  1. Go to your Netlify dashboard and click on your project.
  2. Click the Access tab.
  3. Under Authentication Providers, click Install Provider.
  4. Select GitHub and enter the Client ID and Client Secret, then save.

Access the CMS

With the site deployed and authentication in place, you’ll be able to enter the CMS by going to the URL of your new site and appending /admin.

Gatsby

This guide will help you get started using Netlify CMS and Gatsby.

To get up and running with Gatsby, you’ll need to have Node.js installed on your computer. Note: Gatsby’s minimum supported Node.js version is Node 8.

Create a new Gatsby site

Let’s create a new site using the default Gatsby Starter Blog. Run the following commands in the terminal, in the folder where you’d like to create the blog:

npm install -g gatsby-cli
gatsby new blog https://github.com/gatsbyjs/gatsby-starter-blog
cd blog

Get to know Gatsby

In your favorite code editor, open up the code generated for your “Gatsby Starter Blog” site, and take a look at the content directory.

You will see that there are multiple Markdown files that represent blog posts. Open one .md file and you will see something like this:

---
title: New Beginnings
date: "2015-05-28T22:40:32.169Z"
description: This is an optional description for SEO and Open Graph purposes, rather than the default generated excerpt.
---

Far far away, behind the word mountains, far from the countries Vokalia and
Consonantia, there live the blind texts.

We can see above that each blog post has a title, a date, a description and a body. Now, let’s recreate this using Netlify CMS.

Add Netlify CMS to your site

First let’s install some dependencies. We’ll need netlify-cms-app and gatsby-plugin-netlify-cms. Run the following command in the terminal at the root of your site:

npm install --save netlify-cms-app gatsby-plugin-netlify-cms

Configuration

For the purpose of this guide we will deploy to Netlify from a GitHub repository which requires the minimum configuration.

Create a config.yml file in the directory structure you see below:

├── static
│   ├── admin
│   │   ├── config.yml

In your config.yml file paste the following configuration:

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'
    create: true
    slug: 'index'
    media_folder: ''
    public_folder: ''
    path: '{{title}}/index'
    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' }

Note: The above configuration allows assets to be stored relative to their content. Therefore posts would be stored in the format below as it is in gatsby-starter-blog.

content/
├── blog
│   ├── first-post-title
│   │   ├── index.md
│   │   └── post-image.jpg
└── └── second-post-title
        ├── index.md
        └── post-image.jpg

Finally, add the plugin to your gatsby-config.js.

plugins: [`gatsby-plugin-netlify-cms`]

Push to GitHub

It’s now time to commit your changes and push to GitHub. The Gatsby starter 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

Add your repo to Netlify

Go to Netlify and select ‘New Site from Git’. Select GitHub and the repository you just pushed to. Click Configure Netlify on GitHub and give access to your repository. Finish the setup by clicking Deploy Site. Netlify will begin reading your repository and starting building your project.

Enable Identity and Git Gateway

Netlify’s Identity and Git Gateway services allow you to manage CMS admin users for your site without requiring them to have an account with your Git host or commit access on your repo. From your site dashboard on Netlify:

  1. Go to Settings > Identity, and select Enable Identity service.
  2. Under Registration preferences, select Open or Invite only. In most cases, you want only invited users to access your CMS, but if you’re just experimenting, you can leave it open for convenience.
  3. If you’d like to allow one-click login with services like Google and GitHub, check the boxes next to the services you’d like to use, under External providers.
  4. Scroll down to Services > Git Gateway, and click Enable Git Gateway. This authenticates with your Git host and generates an API access token. In this case, we’re leaving the Roles field blank, which means any logged in user may access the CMS. For information on changing this, check the Netlify Identity documentation.

Start publishing

It’s time to create your first blog post. Login to your site’s /admin/ page and create a new post by clicking New Blog. Add a title, a date and some text. When you click Publish, a new commit will be created in your GitHub repo with this format Create Blog “year-month-date-title”.

Then Netlify will detect that there was a commit in your repo, and will start rebuilding your project. When your project is deployed you’ll be able to see the post you created.

Cleanup

It is now safe to remove the default Gatsby blog posts.

Hugo

Introduction

This guide will walk you through how to integrate Netlify CMS with Hugo. This is a good place to start if you want to learn from the ground up how these two tools work together. If you want to get up-and-running quicker, you can use one of the pre-existing and amazing starter templates!

Getting started with Hugo

Installation

To get started with Hugo, you should first install the command line tool. If you’ve already got it installed, you can skip this step. On MacOS and Linux you can do this with:

brew install hugo

To test that it’s successfully installed, you can try this command, to get a list of Hugo’s options:

hugo help

Creating a new site

Create a new Hugo project and start it up using the following commands.

hugo new site <name-of-your-new-project>
cd <name-of-your-new-project>
hugo server

You won’t actually see anything, just yet, and that’s because you don’t have any template files. That’s easily resolved. In the layouts/ directory, create a file index.html and put a basic HTML structure in there:

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <meta http-equiv="X-UA-Compatible" content="ie=edge" />
    <title>Document</title>
  </head>
  <body>
    <h1>Nice. It's looking good already.</h1>
  </body>
</html>

You’ll also add some files to the content/ and data/ directories to make sure git tracks them.

touch content/.keep data/.keep

This is as basic as you can get with a Hugo project. There’s just enough here now for us to install Netlify CMS.

Getting Started With Netlify CMS

Add the Netlify CMS files to Hugo

In Hugo, static files that don’t need to be processed by the build commands live in the static/ directory. You’ll install the Netlify CMS admin and config files there. Create a directory admin/ and within it, create two files index.html and config.yml. In the index.html, add the following content:

<!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>

In the config.yml file, you can add this basic configuration — you can customize as you see fit, this sample file is just to get you started.

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'
    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' }

Note: You won’t be able to access the CMS just yet — you still need to deploy the project with Netlify and authenticate with Netlify Identity. You’ll handle this in the next few steps of this guide.

Pushing to GitHub

It’s now time to commit your changes and push to GitHub. You can run the following commands to initialize a git repository and push the changes so far.

git init # Initialize a git repository
git add . # Add every file
git commit -m "Initial Commit" # Commit every file with the message 'Initial Commit'
git remote add origin https://github.com/YOUR_USERNAME/NEW_REPO_NAME.git # Create a new repo on GitHub and add it to this project as a remote repository.
git push -u origin main # Push your changes

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 hugo and the publish directory to public. 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 layouts/index.html, we can add the following to the <head> tag on the page:

<script src="https://identity.netlify.com/v1/netlify-identity-widget.js"></script>

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

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:1313/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.

And that’s it! From this point on, it’s just a matter of following the Hugo documentation for outputting the content from your content/ directory into templates! For more information on configuring Netlify CMS, feel free to check out the Netlify CMS configuration options documentation.

Using Netlify CMS content in Hugo

Creating a list of posts

In your layouts/index.html file, you’ll create an unordered list element and use a Hugo range to output all posts. Inside that range, you can add a list item element with each post title and a link to the post inside it.

Note: To learn more about Hugo’s range function, check out the Hugo documentation.

<body>
  <h1>Nice. It's looking good already.</h1>
  <ul>
    {{ range (where .Pages "Section" "blog") }}
    <li>
      <a href="{{ .RelPermalink }}">
        {{ .Title }}
      </a>
    </li>
    {{ end }}
  </ul>
</body>

That link won’t work just right just yet. You’ll need to make a single page layout for blog posts, so Hugo can create a page for the .RelPermalink to link to.

Creating a single page post layout

Create a file layouts/blog/single.html, and put the following content in there:

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <meta http-equiv="X-UA-Compatible" content="ie=edge" />
    <title>{{ .Title }}</title>
  </head>
  <body>
    <h1>{{ .Title }}</h1>
    <p class="date">{{ .Date }}</p>
    <p class="description">{{ .Params.description }}</p>
    <article class="content">
      {{ .Content }}
    </article>
  </body>
</html>

You can see this basic template includes all the fields you’ve specified in your Netlify CMS config.yml file. You can access any custom front-matter fields with .Params.<field-name>!

Using Hugo shortcodes in the Markdown Editor

Using registerEditorComponent we can register a block level component for the Markdown editor. You can use it to add Hugo’s inbuilt shortcodes like gist,youtube and others as block components to the markdown editor.

You can refer to registering editor components for a getting started guide or for creating your own editor components.

Example

CMS.registerEditorComponent({
    id: "gist",
    label: "Gist",
    fields: [{
            name: "username",
            label: "Github Username",
            widget: "string"
        },
        {
            name: "gid",
            label: "Gist ID",
            widget: "string"
        },
    ],
    pattern: /^{{< gist ([a-zA-Z0-9]+) ([a-zA-Z0-9]+) >}}/,
    fromBlock: function(match) {
        return {
            username: match[1],
            gid: match[2],
        };
    },
    toBlock: function(obj) {
        return `{{< gist ${obj.username} ${obj.gid} >}}`;
    },
    toPreview: function(obj) {
        return '<a href="https://gist.github.com/' + obj.username + '/' + obj.id + '">gist</a>';
    },
});

Result

Gist

For getting started quickly you can refer to this amazing prebuilt resource of hugo shortcodes editor components!