Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Drafts are not being automatically excluded #1523

Open
eduardosada opened this issue Sep 14, 2022 · 6 comments · May be fixed by #2621
Open

Drafts are not being automatically excluded #1523

eduardosada opened this issue Sep 14, 2022 · 6 comments · May be fixed by #2621

Comments

@eduardosada
Copy link

Environment


  • Operating System: Linux
  • Node Version: v16.14.2
  • Nuxt Version: 3.0.0-rc.9
  • Nitro Version: 0.5.2
  • Package Manager: npm@7.17.0
  • Builder: vite
  • User Config: target, typescript, modules, runtimeConfig
  • Runtime Modules: @nuxt/content@2.1.0
  • Build Modules: -

Reproduction

https://stackblitz.com/edit/nuxt-starter-aac1e1?file=pages%2Findex.vue

run:

npm run build
npm run preview

Describe the bug

https://content.nuxtjs.org/guide/writing/markdown

Docs says:

draft | Boolean | false | Mark the page as draft (and only display it in development mode).

But that property doesn't work. I saw from the code that if you put the word 'draft' at the end of a file, it sets the internal _draft property to true. But that doesn't make anything.

eg.:

test.draft.md --> marked as a draft

Currently all drafts are displayed in development and production mode.

Additional context

No response

Logs

No response

@Ratismal
Copy link

Ratismal commented Mar 19, 2023

Want to give my perspective on this. There's some confused reactions, so hopefully this will clarify things.

The documentation advertises a draft property. Assumedly, if a piece of content is marked as a draft, it should be visible when viewing the site in development mode, but should be excluded when the site is viewed in production mode.

A use case for this would be, for example, if content authors want to write and commit drafts of content without it being visible to the public if the site is deployed before it's finished.

Another use case would be to queue up content that is ready to be released, but shouldn't be publicly accessible yet due to a release schedule. This is my personal use case - I'd like to be able to proofread content in development mode but I don't want things to release early.

The documentation is misleading, as this functionality doesn't actually exist in any capacity.

First of all, the draft property is a reserved keyword, as seen here:

If the property draft is set in the front-matter of content, it cannot even be queried against, as the field is reserved and gets excluded from queries.

It's possible that this is actually a bug - looking at the ContentRenderer.vue component, draft is used in a query! However, since it's a reserved field, it has no effect whatsoever.

Every other draft reference to drafts in the codebase are to the _draft property. One would assume that setting the draft property would set the internal _draft property which can be queried, but this isn't the case. The only way to set the _draft property would be to set it directly in front-matter, or to suffix a filename with .draft (ex. file-name.draft.md).

And unfortunately, other than being set, there is nothing in the codebase that actually takes action with the _draft property, so ultimately it's pointless.


As far as solutions go, the cleanest thing I can think of would be to exclude content altogether during the nitro phase.

I think it would be fairly easy for me to create a PR to accomplish both of these tasks, but I would like feedback about whether or not this would be a good solution before doing so.

As a workaround, I've created a plugin server/plugins/draft.ts that mutilates draft content when on production mode.

export default defineNitroPlugin((nitroApp) => {
  // For some reason, accessing NODE_ENV directly returns "prerender", despite the value being "production" or "development"
  const env = JSON.parse(JSON.stringify(process.env)).NODE_ENV;
  nitroApp.hooks.hook('content:file:afterParse', (file) => {
    if (file._draft && env === 'production') {
      console.log('Mutilating draft file', file._id);
      file._id = 'content:_:draft';
      file.body = {};
      file.title = 'Draft';
      file._path = '/draft';
      file._dir = '/draft';
      file._empty = true;
      file.navigation = false;
    }
  });
});

It's obviously a dirty hack, but it works well enough for my purposes.

Hope this helps! Thank you for your time.

@mkummer225
Copy link

mkummer225 commented Oct 25, 2023

Another workaround that's a little cleaner is to create a module wherein you hook content:context and update the contentContext.ignores property at build time to include draft items.

This removes the dangling draft entries in the cache via @Ratismal's solution

  1. Create a custom module; for example custom_modules/ignoreDrafts.mjs:
import { defineNuxtModule } from "@nuxt/kit";
import fm from "front-matter";
import fs from "fs";

export default defineNuxtModule({
    setup(_options, nuxt) {
        // @ts-ignore
        nuxt.hook("content:context", (contentContext) => {
            const env = JSON.parse(JSON.stringify(process.env)).NODE_ENV;

            const contentDir = nuxt.options.buildDir + "/../content";
            if(env === "production" && fs.existsSync(contentDir)) {
                // Read the sub directories within ./content/ then check each .json or .md file for a draft field
                for (let subdir of fs.readdirSync(contentDir).filter((d) => d != ".DS_Store")) {
                    for (let file of fs.readdirSync(`${contentDir}/${subdir}`).map((f) => `${contentDir}/${subdir}/${f}`)) {
                        try {
                            if (file.endsWith(".json")) {
                                const json = JSON.parse(fs.readFileSync(file));

                                if (json.draft)
                                    contentContext.ignores.push(file.split("/").pop());
                            } else if (file.endsWith(".md")) {
                                const md = fm(fs.readFileSync(file, "utf8"));

                                if (md.attributes?.draft)
                                    contentContext.ignores.push(file.split("/").pop());
                            }
                        } catch (e) {
                            console.log(e);
                        }
                    }
                }

                console.log("Updated contentContext.ignores:", contentContext.ignores);
            }
        });
    },
});
  1. Update your nuxt.config.ts file accordingly (note: your custom module must be before @nuxt/content):
import IgnoreDraftsModule from "./custom_modules/ignoreDrafts.mjs"

export default defineNuxtConfig({
    ...,
    modules: [
        ...,
        // @ts-ignore
        IgnoreDraftsModule,
        "@nuxt/content",
        ...
    ],
    ...
})

@Barbapapazes Barbapapazes mentioned this issue Nov 9, 2023
7 tasks
@preethamrn
Copy link

The workarounds and analysis done by previous commenters was great. If there's no plan to work on fixing this maybe the documentation should be updated? It would definitely have saved me a lot of headache since it's a bit misleading as it is right now.

@mynameisjeffe
Copy link

mynameisjeffe commented Mar 27, 2024

Workaround I use is this

https://content.nuxt.com/get-started/configuration#ignores

export default defineNuxtConfig({
  content: {
    ignores: [
      'hidden',        // any file or folder that contains the word "hidden"
    ]
  }
})

I then append "-hidden" for any contents that are still in draft state.

@XStarlink
Copy link

XStarlink commented Mar 27, 2024

Workaround I use is this

https://content.nuxt.com/get-started/configuration#ignores

export default defineNuxtConfig({
  content: {
    ignores: [
      'hidden',        // any file or folder that contains the word "hidden"
    ]
  }
})

I then append "-hidden" for any contents that are still in draft state.

Instead of doing this Workaround, you can prefix the names of your files inside the content folder with a dot, e.g. .pageName.md, and it will be ignored and therefore not displayed.
It works for folders too.

But I agree that draft: true in the Front-matter should also work as described in the doc here: https://content.nuxt.com/usage/markdown#front-matter

@zrooda
Copy link

zrooda commented Apr 23, 2024

This was an unpleasant surprise when we deployed to prod, but my mistake blindly trusting the documentation. Either way the docs should remove mentioning this feature until it actually works.

@zrooda zrooda linked a pull request Apr 23, 2024 that will close this issue
7 tasks
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging a pull request may close this issue.

7 participants