Code Monkey home page Code Monkey logo

astro-netlify-cms's Introduction

Astro + Netlify CMS

Add Netlify CMS’s admin dashboard to any Astro project

Installation

npm i astro-netlify-cms

What is this?

This is an integration for the Astro site builder, which adds support for Netlify CMS, an open-source, Git-based content management system.

Adding the integration will:

  • Add the Netlify CMS dashboard at /admin (or another route if you prefer)
  • Inject Netlify’s Identity Widget across your site to support logging in to the admin app
  • Run a local proxy server in dev mode to allow local content updates via the CMS

Usually each of these requires individual set up and configuration. Using this integration, you configure your CMS once in astro.config.mjs, sit back, and enjoy!

Looking for a quick way to get started? Try out the Blog Starter with Netlify CMS →

Usage

Adding the integration

To add Netlify CMS to your project, import and use the integration in your Astro config file, adding it to the integrations array.

// astro.config.mjs

import { defineConfig } from 'astro/config';
import NetlifyCMS from 'astro-netlify-cms';

export default defineConfig({
  integrations: [
    NetlifyCMS({
      config: {
        backend: {
          name: 'git-gateway',
          branch: 'main',
        },
        collections: [
          // Content collections
        ],
      },
    }),
  ],
});

Configuration options

You can pass an options object to the integration to configure how it behaves.

adminPath

Type: string
Default: '/admin'

Determines the route where the Netlify CMS admin dashboard will be available on your site.

Feeling nostalgic for WordPress? You could set this to '/wp-admin'!

config

Type: CmsConfig

This option is required. It allows you to configure Netlify CMS with the same options you would use when using Netlify CMS’s config.yml file format.

You can see a full list of configuration options in the Netlify CMS docs.

At a minimum, you must set the backend and collections options:

config: {
  // Use Netlify’s “Git Gateway” authentication and target our default branch
  backend: {
    name: 'git-gateway',
    branch: 'main',
  },
  collections: [
    // Define a blog post collection
    {
      name: 'posts',
      label: 'Blog Posts',
      folder: 'src/pages/posts',
      create: true,
      delete: true,
      fields: [
        { name: 'title', widget: 'string', label: 'Post Title' },
        { name: 'body', widget: 'markdown', label: 'Post Body' },
      ],
    },
  ],
};

previewStyles

Type: Array<string | [string, { raw: true }]>

Sets custom CSS styles to apply in the Netlify CMS preview pane.

You can provide URLs to external CSS stylesheets (Google Fonts for example), paths to local CSS files in your project, or even raw CSS strings:

previewStyles: [
  // Path to a local CSS file, relative to your project’s root directory
  '/src/styles/main.css',
  // An npm module identifier
  '@fontsource/roboto',
  // A URL to an externally hosted CSS file
  'https://fonts.googleapis.com/css2?family=IBM+Plex+Mono&display=swap',
  // Raw CSS!
  ['p { color: red; }', { raw: true }],
];

disableIdentityWidgetInjection

Type: boolean
Default: false

By default, astro-netlify-cms injects Netlify’s Identity Widget across your site to enable authentication. If you only want to inject the widget on the admin route, you can set disableIdentityWidgetInjection: true.

To-do

  • Support registering custom preview components to render content as it is edited.
  • Support registering custom block components for use in the Markdown editor.

astro-netlify-cms's People

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar

astro-netlify-cms's Issues

Issue when adding NetlifyCMS to astro config & using getCollection with render()

Hi, I'm facing an error which I couldn't solve it, I'm using astro getCollection() method then render multi MDXs in same page.

so when I'm using the method before adding the NetlifyCMS everything works fine

export const getContent = async ({
  pageName,
  locale,
}: {
  pageName: PageName;
  locale: string;
}): Promise<AstroComponentFactory[]> => {
  const allContent = (
    await getCollection(pageName, (entry) => entry.id.includes(locale))
  ).sort((a, b) => a.data.order - b.data.order) as CollectionEntry<PageName>[];

  const mdxComponents = await Promise.all(
    allContent.map(async (content) => {
      try {
        // will throw an error
        const { Content } = await content.render();
        return Content;
      } catch (e) {
        console.log(e);
        return null;
      }
    })
  );

  return mdxComponents.filter(
    (component) => component !== null
  ) as AstroComponentFactory[];
};

but when adding NetlifyCMS in integrations like this code below

// when commit this part all works fine
NetlifyCMS({
      config: {
        backend: {
          name: "github",
          branch: "main",
        },
        collections: [
          {
            name: "hero",
            label: "hero section",
            folder: "src/content/home/hero",
            create: true,
            delete: false,
            extension: "mdx",
            format: "frontmatter",
            fields: [
              { name: "title", widget: "string", label: "File Title" },
              {
                widget: "string",
                name: "firstLine",
                label: "First Line",
                required: true,
              },
            ],
          },
        ],
      },
    }),

I'm getting this error

Error: Parse error @:12:102
    at parse (file:///Users/my-user/Desktop/magical-main/node_modules/.pnpm/[email protected]/node_modules/es-module-lexer/dist/lexer.js:2:358)
    at TransformContext.transform (file:///Users/my-user/Desktop/magical-main/node_modules/.pnpm/@[email protected][email protected]/node_modules/@astrojs/mdx/dist/index.js:102:58)
    at Object.transform (file:///Users/my-user/Desktop/magical-main/node_modules/.pnpm/[email protected]/node_modules/vite/dist/node/chunks/dep-3b8eb186.js:44240:62)
    at async loadAndTransform (file:///Users/my-user/Desktop/magical-main/node_modules/.pnpm/[email protected]/node_modules/vite/dist/node/chunks/dep-3b8eb186.js:54896:29)
    at async instantiateModule (file:///Users/my-user/Desktop/magical-main/node_modules/.pnpm/[email protected]/node_modules/vite/dist/node/chunks/dep-3b8eb186.js:55821:10) {
  idx: 464,
  plugin: '@astrojs/mdx-postprocess',
  id: '/Users/my-user/Desktop/magical-main/src/content/home/hero/en.mdx',
  pluginCode: '/*@jsxRuntime automatic @jsxImportSource astro*/\n' +
    'export const frontmatter = {\n' +
    '  "title": "Testing Hero",\n' +
    '  "firstLine": "Crafting softwares with astro and DecapCMS",\n' +
    '  "description": "Hero is a simple, extensible, drop-in replacement for the default Hugo theme.",\n' +
    '  "order": 1\n' +
    '};\n' +
    'export function getHeadings() {\n' +
    '  return [];\n' +
    '}\n' +
    'function _createMdxContent(props) {\n' +
    '  return <><h1>{" "}{frontmatter.title}{" "}</h1>{"\\n"}<h1>{" "}{frontmatter.firstLine}{" "}</h1></>;\n' +
    '}\n' +
    'function MDXContent(props = {}) {\n' +
    '  const {wrapper: MDXLayout} = props.components || ({});\n' +
    '  return MDXLayout ? <MDXLayout {...props}><_createMdxContent {...props} /></MDXLayout> : _createMdxContent(props);\n' +
    '}\n' +
    'export default MDXContent;\n'
}

So what could be the issue here and how to solve it?
*note: If I used.md files it will work fine

for full reff you can see this repo

Update:
I believe it could be astro version in astro-netlify-cms it's older then the one I'm using which is "astro": "^2.9.3",

i18n support

I was wondering if it was possible to use this with i18n support. Is there an example? Would it be possible to combine with a multilingual front page? Or do you need a different package for multilanguage options for the front page like 18next?

Creating a collection for global/page-specific settings

I've just started playing with this integration today and I'm running into a bit of a project design issue. If I wanted to add a collection to NetlifyCMS to use as feature switches (e.g. "show author names on blog landing page"), how should I go about building that so I can read that value in my Astro file and change the page accordingly? I'm still exploring Astro, I don't have any pre-existing file structure to worry about so I'm open to any suggestions.

When I was using 11ty, I would just create a blogSettings.yml file and read directly from that since it gets supplied as global data. I'm not sure what the proper style here would be.

Thanks for your help, appreciate the work you're doing!

entryPoint is deprecated (includes fix)

With Astro v4+, a warning pops up when the dev server is launched:

[WARN] The injected route "/admin" by netlify-cms specifies the entry point with the "entryPoint" property. This property is deprecated, please use "entrypoint" instead.

I've tested and this works by simply replacing entryPoint with entrypoint here:

entryPoint: 'astro-netlify-cms/admin-dashboard.astro',

How to integrate netlify-cms-widget-mdx

This is a very useful starter. One thing which I am not able to figure out is how to integrate netlify-cms-widget-mdx

Being able to support mdx widget (in place of markdown) would be very useful.

Basically where and how to add the following lines:

import { MdxControl, MdxPreview } from 'netlify-cms-widget-mdx';

CMS.registerWidget('mdx', MdxControl, MdxPreview);

Astro/Vite fails to properly mount Vue

After installing astro-netlify-cms and adding a basic config entry in astro.config.mjs, Vue components failed to render as the Vue instance was seemingly not being properly mounted.

Fails to render Vue components

export default defineConfig({
  site: 'https://example.com',
  integrations: [
    mdx(),
    sitemap(),
    vue(),  // Vue integration declared before NetlifyCMS
    NetlifyCMS({
      config: {
        backend: {
          name: 'git-gateway',
          branch: 'master'
        },
        collections: [
          {
            name: 'posts',
            label: 'Blog Posts',
            folder: 'src/pages/blog',
            create: true,
            delete: true,
            fields: [
              { name: 'title', widget: 'string', label: 'Post Title' },
              { name: 'body', widget: 'markdown', label: 'Post Body' },
            ],
          },
        ]
      }
     }),
  ],
});

Properly renders Vue components

export default defineConfig({
  site: 'https://example.com',
  integrations: [
    mdx(),
    sitemap(),
    NetlifyCMS({
      config: {
        backend: {
          name: 'git-gateway',
          branch: 'master'
        },
        collections: [
          {
            name: 'posts',
            label: 'Blog Posts',
            folder: 'src/pages/blog',
            create: true,
            delete: true,
            fields: [
              { name: 'title', widget: 'string', label: 'Post Title' },
              { name: 'body', widget: 'markdown', label: 'Post Body' },
            ],
          },
        ]
      }
     }),
     vue(),
  ],
});

I'm not sure if this is an issue specific to the Astro-Netlify-CMS integration, or if it's on the Astro / Astro Vue integration side of things. However, it was difficult to figure out the cause other than that it having occurred after setting up Astro-Netlify-CMS.

In case it helps to identify the source, here's the error messages I was getting.

When rendering Vue components without a client directive:

[plugin:vite:vue] Attribute name cannot contain U+0022 ("), U+0027 ('), and U+003C (<)

When they are passed a client:only directive:

Vue warn: Component is missing template or render function

Perhaps it's worth mentioning in the installation / config instructions that this can be resolved by declaring the Astro-Netlify-CMS integration prior to Vue.

What if you need to update the theme?

Directly reference the layout and code of the theme. What if you need to update the theme? It's a bigger problem for you to switch themes. Do you consider providing module references

is it posible to only load the identity-widget on the /admin route?

At the moment the identity widget + the webpack://components/modal.css is served on every page.
those 2 are the biggest files on every page.

is there a way to bind the scripts and styles to the /admin only?

We then can just have a small function on the homepage that looks if there is a password reset #hash present and redirect to the admin.

https://www.my-website.com/#recovery_token=<token> => https://www.my-website.com/admin/#recovery_token=<token>

Issues implementing layout to blog posts.

I am currently learning how to use astro-netlify-cms to create a sample blogging and I am having trouble implementing the layout for the blogs.

My folder structure looks like the following

-src
-layouts
-MarkdownPostLayout.astro
-pages
-posts
-blog1.md
astro.config.mjs

Here is my astro.config.mjs file:
https://github.com/Albertyhu/astro-blog-with-netlify-cms/blob/main/astro.config.mjs

In collections, I set the field layout to the following:

{
          name: "layout",
          widget: "hidden",
          label: "Layout",
          default: `import layout from '../../layouts/MarkdownPostLayout.astro'`,
        },

Here is the Github repository for the rest of the project: https://github.com/Albertyhu/astro-blog-with-netlify-cms/tree/main

I appreciate any help I can get here.

Customize admin-dashboard.astro layout

This is a feature request - the plugin is great to quickly add the Netlify CMS to an Astro project, but eliminates the ability to modify the /admin page (favicon, title, additional stylesheets, etc.) as it's bundled with the package.

It would be great to expose an optional admin-layout.astro file that could be used to customize the dashboard. Not sure what the best path forward is, but I may end up dropping the package and configuring everything manually so I can retain control over the admin.html page.

Is there an easy way to modify the admin page currently?

add Netlify identity widget on admin route

Currently if you don't set disableIdentityWidgetInjection to true then it add the Netlify Identity Widget to all page which can lead to unnecessary ressource being loaded in most case.

I would be nice to have a options to only inject it on admin routes.

Security warnings when I use this repo

Adding this package to my Astro installation will trigger npm audit without being able to fix it because some dependency packaging has an hard coded semantic version. Could you check it please?

Oauth Gateway not working

Hello,

I have integrated the plugin correctly and works ok on localhost. Before using this plugin, I used the tutorial from Astro blog with Netlify CMS integration, and all worked well on prod.

Later on, I switched to this plugin, and seems that in prod I can see this ugly page :(.
The "pop-up" to login with Github doesn't show...

Captura de pantalla 2023-09-26 a las 20 24 55

Error: spawn netlify-cms-proxy-server ENOENT on "astro dev

Working on a Windows OS and running astro dev returns the following error.

node:events:368
      throw er; // Unhandled 'error' event
      ^

Error: spawn netlify-cms-proxy-server ENOENT
    at Process.ChildProcess._handle.onexit (node:internal/child_process:282:19)
    at onErrorNT (node:internal/child_process:477:16)
    at processTicksAndRejections (node:internal/process/task_queues:83:21)
Emitted 'error' event on ChildProcess instance at:
    at Process.ChildProcess._handle.onexit (node:internal/child_process:288:12)
    at onErrorNT (node:internal/child_process:477:16)
    at processTicksAndRejections (node:internal/process/task_queues:83:21) {
  errno: -4058,
  code: 'ENOENT',
  syscall: 'spawn netlify-cms-proxy-server',
  path: 'netlify-cms-proxy-server',
  spawnargs: []
}

when I manually start the proxy server and comment out:

/* 'astro:server:start': () => {
                const proxy = spawn('netlify-cms-proxy-server', { stdio: 'inherit' });
                process.on('exit', () => proxy.kill());
            }, */

it works.

Undefined disableIdentityWidgetInjection causes script to be injected onto every page

Hey there!

I've just noticed that a script page.<hash>.js is injected into every page when using this integration with the default config from the Astro Netlify CMS Starter.

I'm unsure whether this is the desired behavior. I've read that the identity widget is used if you're hosting the blog+cms on Netlify and do not use a git hosting provider such as github. So backend: git-gateway, hosted on Netlify without github et al.

Steps to reproduce

I'm opening this issue because I'm not sure if this is a bug or desired.
Thank you!

I can't log in to Netlify CMS

Hi @delucis 👋

I am a complete newbie to Astro and Netlify CMS. I have a problem logging into the Netlify CMS administration.

I have installed astro-netlify-cms and edited the astro.config.mjs config as needed (see below).

import { defineConfig } from 'astro/config';
import NetlifyCMS from 'astro-netlify-cms';
import preact from "@astrojs/preact";

export default defineConfig({
  integrations: [
    NetlifyCMS({
      config: {
        backend: {
          name: 'git-gateway',
          branch: 'master',
        },
        collections:  [
          {
            name: 'posts',
            label: 'Blog posts',
            folder: 'src/pages/posts',
            create: true,
            delete: true,
            fields: [
            { name: 'title', widget: 'string', label: 'Post title' },
            { name: 'body', widget: 'markdown', label: 'Post body'},
            ],
          },
        ],
      },
    }),
    preact()]
});

I committed everything to the repository on GitHub. In the netlify app I added a new site with the following settings:

Base directory: Not set
Build command: npm run build
Publish directory: dist
Deploy log visibility: Logs are public
Build status: Active

I also enabled Identity and Git gateway. The first thing I noticed is that the site doesn't show the login widget. When I add /admin, it takes me to the Netlify CMS login page, but shouldn't the registration option pop up first?

You can check the site yourself - www.stpn.dev
Then here is my repo - stpn-astro

I don't really know where to look for the error and that's why I would like to ask for help.

Build failing with demo and Astro 1.4.4

Trying to build with Astro 1.4.4 and failing:

generating static routes error component is not defined ReferenceError: component is not defined atfile:///Users/psmith/Sites/nw-3-deploy-testing/test/.astro/entry.mjs?time=1665061500569:1780:25``

line 1780:

__astro_tag_component__(component, "@astrojs/react");

package.json:

{ "name": "@example/blog", "version": "0.0.1", "private": true, "scripts": { "dev": "astro dev", "start": "npm run dev", "build": "astro build", "preview": "astro preview" }, "devDependencies": { "astro": "^1.4.4", "astro-netlify-cms": "^0.2.2" } }

Error: spawn netlify-cms-proxy-server ENOENT on "astro dev

I'm getting the following error on astro dev.

Running Mac Os Ventura
PNPM is my package manager


  🚀  astro  v1.7.2 started in 333ms
  
  ┃ Local    http://localhost:3000/
  ┃ Network  use --host to expose
  
node:events:491
      throw er; // Unhandled 'error' event
      ^

Error: spawn netlify-cms-proxy-server ENOENT
    at ChildProcess._handle.onexit (node:internal/child_process:283:19)
    at onErrorNT (node:internal/child_process:476:16)
    at process.processTicksAndRejections (node:internal/process/task_queues:82:21)
Emitted 'error' event on ChildProcess instance at:
    at ChildProcess._handle.onexit (node:internal/child_process:289:12)
    at onErrorNT (node:internal/child_process:476:16)
    at process.processTicksAndRejections (node:internal/process/task_queues:82:21) {
  errno: -2,
  code: 'ENOENT',
  syscall: 'spawn netlify-cms-proxy-server',
  path: 'netlify-cms-proxy-server',
  spawnargs: []
}

Node.js v18.12.1
 ELIFECYCLE  Command failed with exit code 1.```

Netlify CMS dashboard won't work if `vue()` is added after `NetlifyCMS()` in `astro.config.mjs`

Kinda follow up of #18 , this time if I move vue() like this:

// https://astro.build/config
export default defineConfig({
  integrations: [NetlifyCMS({...}), vue()],
  site: `whatever`,
  output: 'static',
});

Instead of this:

// https://astro.build/config
export default defineConfig({
  integrations: [vue(), NetlifyCMS({...})],
  site: `whatever`,
  output: 'static',
});

like title, NetlifyCMS won't show up

`netlify-cms-app` import failed to resolve with astro's react integration

Running into the following error:

Screenshot_20221215_203933

Seems to be related to #34 , but with react() instead of vue() added as integration.
Makes no difference if putting it before or after NetlifyCMS() in the config.
The admin dashboard is working perfectly fine without the react integration and dependencies.

Will provide a cleaned repo to reproduce the issue later.

Invite/reset emails point to a wrong URL when using i18next with `showDefaultLocale: true`

Hi there and thanks for this great integration :)

I have everything up and running and it worked great, until I turned on showDefaultLocale to true in my i18next config file.

What this does is that instead of having the urls for the default language on /, they are on /en. (i.e. /blog becomes /en/blog)

So for the homepage, as stated in Astro's docs, I just have this src/pages/index.astro:

<meta http-equiv="refresh" content="0;url=/en/" />

Which just redirects from / to /en.

But then the links in the emails sent by Netlify upon registration or forgotten email all point to /#invite_token=2EUz71D9siVlVLJjsPhj1w which then redirects to /en without the extra #invite_token.

Would there be a way to specify the URL in the emails to be /en ?

Or could we change src/pages/index.astro so that upon redirecting it preserves the #invite_token ?

Thank you so much :)

Automatically generate collections from Content Collections

Hey, this feature could be great but not sure how difficult or feasible it is.

You could automatically generate DecapCMS config's collections based on the the Content Collections schemas.

This way we can have a single schema fields definition, and boilerplates a CMS really fast!

admin page is blank, 404 error trying to get admin-dashboard.astro

So far I installed the package, pasted the necessary code into astro.config.mjs. This is what I get when visiting /admin

image

config:

import { defineConfig } from 'astro/config';
import svelte from "@astrojs/svelte";
import NetlifyCMS from 'astro-netlify-cms';
import mdx from "@astrojs/mdx";

// https://astro.build/config
export default defineConfig({
  site: 'https://kodvet.gitlab-pages.liu.se/',
  base: '/sektionshemsidan',
  // Your public domain, e.g.: https://my-site.dev/. Used to generate sitemaps and canonical URLs.
  // base: 'kvit/',
  sitemap: true,
  // Generate sitemap (set to "false" to disable)
  // GitLab Pages requires exposed files to be located in a folder called "public".
  // So we're instructing Astro to put the static build output in a folder of that name.
  outDir: 'public',
  // The folder name Astro uses for static files (`public`) is already reserved
  // for the build output. So in deviation from the defaults we're using a folder
  // called `static` instead.
  publicDir: 'static',
  integrations: [NetlifyCMS({
      config: {
        backend: {
          name: 'git-gateway',
          branch: 'main',
        },
        media_folder: 'public/assets/blog',
        public_folder: '/assets/blog',
        collections: [
          // Content collections
          {
      name: 'posts',
      label: 'Blog Posts',
      folder: 'src/pages/posts',
      create: true,
      delete: true,
      fields: [
        { name: 'title', widget: 'string', label: 'Post Title' },
        { name: 'body', widget: 'markdown', label: 'Post Body' },
      ],
    }
        ],
      },
    }), svelte(), mdx()]
});

Localization

Hi,

is there a way to set a specific localization for my NetlifyCMS with this library?
I know you can set the locale with this code:
import CMS from 'netlify-cms-app'; import { de } from 'netlify-cms-locales'; CMS.registerLocale('de', de);
But I don't know of a way to pass this to the NetlifyCMS integration

Thanks in advance

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.