Skip to content

Relative markdown links between blog and docs does not work #9117

Open

Description

@quinn-p-mchugh

Have you read the Contributing Guidelines on issues?

Prerequisites

Description

Hi Docusaurus team,

Love this library - thank you for your awesome work!

I'm looking to link a blog post to a docs page using a relative markdown link, but I receive the following error when I specify [link to doc](../../docs/doc-page.md) in the blog post:

[WARNING] Blog markdown link couldn't be resolved: (../../docs/doc-page.md) in "/home/projects/github-dc5ygn/blog/blog-post.md

On the other hand, using link without the .md ([link to doc](../../docs/doc-page)) extension works fine.

Is there a way I can prevent the broken link while preserving the .md extension? I'm using an Obsidian plugin to convert wikilinks to internal links and need to keep the .md extension for it to work properly.

Reproducible demo

https://stackblitz.com/edit/facebook-docusaurus-mx3fkh?file=blog%2Fblog-post.md

Steps to reproduce

  1. Go to demo linked above.
  2. Wait for the site to compile. You should see a warning: [WARNING] Docs markdown link couldn't be resolved: (../../docs/doc-page.md) in "/home/projects/facebook-docusaurus-mx3fkh/docs/doc-page.md" for version current
  3. In the website preview on the right, click the menu button (three bars).
  4. Click Blog.
  5. Under the "blog-post" title click "link to doc".
  6. You should see a "Page Not Found" error.
  7. Edit "blog-post.md" to exclude ".md" from the link: [link to doc](../../docs/doc-page)
  8. Complete steps 2-5. Link should now work correctly.

Expected behavior

The link [link to doc](../../docs/doc-page) should work regardless of whether or not .md is specified.

Actual behavior

The link [link to doc](../../docs/doc-page) only works when .md is omitted.

Your environment

  • Public source code: See demo link above
  • Public site URL: See demo link above
  • Docusaurus version used: 2.4.1
  • Environment name and version (e.g. Chrome 89, Node.js 16.4): Node.js 16.20.0
  • Operating system and version (e.g. Ubuntu 20.04.2 LTS): N/A

Self-service

  • I'd be willing to fix this bug myself.

Activity

  1. added
    bug
    status: needs triage
    on Jul 1, 2023
  2. removed
    status: needs triage
    on Jul 3, 2023
  3. slorber commented on Jul 3, 2023

    @slorber
    Collaborator

    Yes, it does not work, because currently the relative link resolution is a plugin-specific feature and not a Docusaurus core feature.

    I'd like to support cross-plugin relative links but it would require the core engine to somehow maintain a "file path -> URL path" mapping, and we probably need additional plugin lifecycle hooks for that.

    Note: if you use Docs versioning, once your docs get versioned, the docs copy will be at a different location and it might break your relative links that are not linking to the same current version (I mean: a relative link from v1.3 to v1.3 won't break, but a v1.3 relative link to a blog post might break when the doc is moved from ./docs to ./versioned_docs/1.3).

  4. quinn-p-mchugh commented on Jul 3, 2023

    @quinn-p-mchugh
    Author

    Hi @slorber,

    Thanks for confirming! I now see this is noted in the documentation here.

    Good to know regarding doc versioning. Fortunately, I do not have a need for versioned docs at this time.

    Seems like I might be able to workaround this by using regular expressions to remove the .md in the GitHub Obsidian Publisher settings, but we'll see.

    Very much appreciate your help.

  5. added
    difficulty: advanced
    domain: markdown
    on Jul 16, 2023
  6. ADNANALISALHADABY commented on Aug 28, 2023

    @ADNANALISALHADABY
  7. AMD-NICK commented on Jan 29, 2025

    @AMD-NICK

    related #3250

  8. octogonz commented on Aug 11, 2026

    @octogonz

    I encountered this same issue. A couple notes:

    The classic workaround was URL links, which is what Docusaurus's own blog does. For example it uses /docs/api/docusaurus-config#markdown in pages coming from the blog to the docs. The corresponding config would be: onBrokenMarkdownLinks: 'warn' with onBrokenLinks and onBrokenAnchors set to throw. It works, but it means you need to memorize two different linking syntaxes, and every time you write a hyperlink, you now must stop and ask "is the target URL under a different plugin instance?" Nor does it help the original reporter, who said they need the .md extension preserved for Obsidian tooling.

    Docusaurus 3.9.0 added an API that can provide a better workaround. siteConfig.markdown.hooks (#11283) allows onBrokenMarkdownLinks to be a function, and resolveMarkdownLinks uses its return value to replace the link URL. Since the hook only fires for links Docusaurus already failed to resolve, this approach won't change the behavior of any link that already works today. Pair it with a small plugin that uses allContentLoaded() to build a site-wide map of source file path to permalink, and relative .md links work in every direction. There are probably feature interactions that break, so official support would still be superior to this workaround.

    Below is my script in case anyone else finds it helpful:

    crossPluginLinks.ts

    import * as path from 'path';
    import { pathToFileURL, fileURLToPath } from 'url';
    import type { AllContent, LoadContext, Plugin, OnBrokenMarkdownLinksFunction } from '@docusaurus/types';
    
    /**
     * Fixes an error like this, where a blog post links to a docs page:
     *
     * ```
     * Error: MDX compilation failed for file "blog/2020-01-01-hello-world.md"
     * Cause: Blog markdown link couldn't be resolved: (../docs/getting-started.md)
     * ```
     *
     * The link is correct on disk, but Docusaurus only resolves relative .md links within a
     * single plugin instance.  (See https://github.com/facebook/docusaurus/issues/9117)
     *
     * USAGE: in docusaurus.config.ts, create the pair and install both halves:
     *
     * ```ts
     * import { createCrossPluginLinks } from './src/plugins/crossPluginLinks';
     *
     * const crossPluginLinks = createCrossPluginLinks();
     *
     * const config: Config = {
     *   markdown: {
     *     hooks: {
     *       onBrokenMarkdownLinks: crossPluginLinks.resolveMarkdownLink
     *     }
     *   },
     *   plugins: [crossPluginLinks.plugin]
     * };
     * ```
     *
     * Both halves are required: `plugin` builds the index, `resolveMarkdownLink` consumes it.
     * Import the module directly as shown.  Do not load `plugin` via `require.resolve()`, which
     * would give the two halves separate copies of the index and resolve nothing.
     *
     * `resolveMarkdownLink` replaces the `onBrokenMarkdownLinks: 'throw'` setting, and still
     * throws for links that are genuinely broken.  Set `onBrokenAnchors: 'throw'` as well, since
     * a `#hash` suffix is carried across to the target page unvalidated.
     *
     * LIMITATIONS:
     *
     * - Versioned docs are not supported.  `docusaurus docs:version` copies the docs tree to a
     *   different depth under `versioned_docs/`, so any relative link that points outside that
     *   tree is silently wrong in the snapshot, and this will report it as broken.
     * - Links are matched by exact path, so the case must match on all platforms, as it already
     *   must for Docusaurus's own same-plugin link resolution.
     */
    
    // avoid dev dependencies
    interface IDocsLikeContent {
      loadedVersions: {
        docs: {
          source: string;
          permalink: string;
        }[];
      }[];
    }
    
    interface IBlogLikeContent {
      blogPosts: {
        metadata: {
          source: string;
          permalink: string;
        };
      }[];
    }
    
    export interface ICrossPluginLinks {
      /** Add to `plugins` in docusaurus.config.ts */
      plugin: (context: LoadContext) => Plugin;
    
      /** Assign to `markdown.hooks.onBrokenMarkdownLinks` in docusaurus.config.ts */
      resolveMarkdownLink: OnBrokenMarkdownLinksFunction;
    }
    
    export function createCrossPluginLinks(): ICrossPluginLinks {
      // Absolute source file path -> permalink, covering every content plugin instance
      const sourceToPermalink: Map<string, string> = new Map();
    
      let siteDir: string | undefined = undefined;
    
      function registerFile(source: string, permalink: string): void {
        // "source" uses the alias syntax "@site/docs/machine/io/gamepads.md"
        const absolutePath: string = path.resolve(siteDir as string, source.replace(/^@site[\\/]/, ''));
        sourceToPermalink.set(absolutePath, permalink);
      }
    
      function plugin(context: LoadContext): Plugin {
        siteDir = context.siteDir;
    
        return {
          name: 'cross-plugin-links',
    
          // Docusaurus runs this after every plugin has loaded its content, and before webpack
          // compiles any Markdown.  It also re-runs on dev server reloads.
          allContentLoaded: (args: { allContent: AllContent }): void => {
            const allContent: AllContent = args.allContent;
    
            sourceToPermalink.clear();
    
            for (const instanceContent of Object.values(allContent['docusaurus-plugin-content-docs'] ?? {})) {
              const docsContent: IDocsLikeContent | null = instanceContent as IDocsLikeContent | null;
              for (const version of docsContent?.loadedVersions ?? []) {
                for (const doc of version.docs) {
                  registerFile(doc.source, doc.permalink);
                }
              }
            }
    
            for (const instanceContent of Object.values(allContent['docusaurus-plugin-content-blog'] ?? {})) {
              const blogContent: IBlogLikeContent | null = instanceContent as IBlogLikeContent | null;
              for (const post of blogContent?.blogPosts ?? []) {
                registerFile(post.metadata.source, post.metadata.permalink);
              }
            }
    
            console.log(`==> cross-plugin-links indexed ${sourceToPermalink.size} content files`);
          }
        };
      }
    
      const resolveMarkdownLink: OnBrokenMarkdownLinksFunction = ({ sourceFilePath, url, node }) => {
        // Despite the type declaration's docstring, Docusaurus passes sourceFilePath relative to
        // process.cwd() (via toMessageRelativeFilePath).  Our build always runs with
        // cwd === siteDir, but resolve against both to be safe.
        for (const baseDir of [process.cwd(), siteDir]) {
          if (baseDir === undefined) {
            continue;
          }
          const absoluteSource: string = path.resolve(baseDir, sourceFilePath);
    
          // Resolving against a file:// URL splits off "?query#hash", applies the relative path,
          // and percent-decodes the result.  A link such as "https://x.com/y.md" or "mailto:..."
          // parses with its own protocol instead, and is left for Docusaurus to handle.
          const targetUrl: URL = new URL(url, pathToFileURL(absoluteSource));
          if (targetUrl.protocol !== 'file:' || targetUrl.host !== '') {
            break;
          }
    
          const suffix: string = targetUrl.search + targetUrl.hash;
          targetUrl.search = '';
          targetUrl.hash = '';
    
          const permalink: string | undefined = sourceToPermalink.get(fileURLToPath(targetUrl));
          if (permalink !== undefined) {
            return permalink + suffix;
          }
        }
    
        // Genuine mistakes must still break the build (equivalent to the old "throw" setting)
        const line: number | undefined = node.position?.start.line;
        throw new Error(
          `Broken Markdown link "${url}" in "${sourceFilePath}"${line !== undefined ? ` at line ${line}` : ''}\n` +
            `The target was not found in this plugin instance, nor in the cross-plugin index of ` +
            `${sourceToPermalink.size} content files.`
        );
      };
    
      return { plugin, resolveMarkdownLink };
    }
  9. gauranshahuja commented on Sep 9, 2026

    @gauranshahuja

    I'd like to work on this.

    Plan, building on @slorber's sketch above and @octogonz's workaround: a core source-file-path → permalink registry, filled in allContentLoaded by the docs, blog and pages plugins (multi-instance and versioned docs included), and consulted by resolveMarkdownLinks in @docusaurus/utils as a fallback after the existing per-plugin lookup, so any link that resolves today is unchanged. Relative .md links then work in every direction, and the .md extension the original report needs is preserved.

    I'll post a short design note here (registry shape, where the lifecycle hook lands, how versioned docs are keyed) before opening the PR, so the approach can be checked first.

  10. gauranshahuja commented on Sep 9, 2026

    @gauranshahuja

    Edit: superseded by my later note below and by #12431, which build the registry from route metadata instead of adding a plugin lifecycle. Leaving this here for the record.

    Design note before I open the PR, building on @slorber's "file path -> URL path" sketch and @octogonz's hook based workaround.

    Registry: a site wide Map from source path to permalink, owned by core and exposed to plugins on LoadContext (working name siteSourceToPermalink). Keys are the same @site/... aliased paths the docs, blog and pages plugins already use in their own sourceToPermalink maps, so versioned docs (@site/versioned_docs/version-1.0/x.md) and multi instance docs (@site/community/x.md) are keyed by their real file location with no special casing.

    Filling it: a new optional plugin lifecycle, getSourceToPermalink({content}), returning that instance's map. Core calls it for every loaded plugin and rebuilds the registry in executeAllPluginsAllContentLoaded, just before the allContentLoaded hooks. reloadPlugin goes through the same function, so dev server reloads stay correct (the case #10185 fixed with the mutable maps).

    Lookup: resolveMarkdownLinkPathname in @docusaurus/utils takes an optional siteSourceToPermalink and tries the same candidate paths against it only after the per plugin map misses. Links that resolve today are untouched. onBrokenMarkdownLinks still fires when both miss, so the hook workaround keeps working. Query and hash handling stay in the remark plugin.

    Known limits, unchanged from today: a relative link written in docs/ breaks after docs:version copies the file one directory deeper (site absolute /blog/post.md is the stable form, I will document it), and localized targets are keyed by their i18n/ path.

    Is this shape acceptable, in particular a new lifecycle rather than core reading allContent by plugin name?

  11. gauranshahuja commented on Sep 10, 2026

    @gauranshahuja

    Update: this is now implemented and tested on my branch, PR incoming. Design note below, as promised. Building on @slorber's "core maintains a file path → URL path mapping" comment above and @octogonz's workaround plugin. (AI-assisted)

    Goal

    A .md / .mdx link whose target is owned by another plugin instance (docs → blog, blog → docs, pages → docs, docs instance A → docs instance B) resolves to the target's permalink, with the same link syntax that already works inside a plugin. Every link that resolves today keeps resolving exactly as it does now.

    1. Registry shape

    Nothing new: the existing SourceToPermalink map (Map<'@site/<posix path>', permalink>), just site-wide. Keeping the same key format means resolveMarkdownLinkPathname() in @docusaurus/utils is reused unchanged for the fallback, called with the site-wide map and contentPaths = {contentPath: siteDir}:

    • /blog/2023-01-01-hello.md → <siteDir>/blog/2023-01-01-hello.md
    • ../blog/2023-01-01-hello.md → relative to the linking file
    • @site/blog/2023-01-01-hello.md → direct lookup

    2. Who fills it: core, from the routes. No new lifecycle hook needed.

    Since #10457 every route emitted by docs, blog and pages carries metadata.sourceFilePath (relative to siteDir). Core builds the site-wide map right after loadPlugins():

    flattenRoutes(routes)
      .filter((r) => r.metadata?.sourceFilePath)
      .forEach((r) => map.set(`@site/${r.metadata.sourceFilePath}`, r.path));

    That gives multi-instance, versioned docs and i18n for free, and any third-party content plugin joins the moment it sets sourceFilePath on its routes (which it should already do for the last-updated / sitemap metadata). If two routes point at the same source file, the first one wins and we log a warning; in practice this only happens with duplicated content. An explicit "register a source without a route" API can be added later if a plugin ever needs it; I'd rather not add plugin API surface in v1.

    3. Resolution order in the resolveMarkdownLinks remark plugin

    1. the plugin's own resolveMarkdownLink (unchanged, always first);
    2. if it returns null, the site-wide lookup;
    3. if still nothing, onBrokenMarkdownLinks as today.

    Because the plugin's own map wins, ./intro.md inside docs keeps pointing at the docs page even if src/pages/intro.md exists. The error message drops the "within the current plugin" wording.

    4. Getting the map into the MDX loader (the part that needs a decision)

    configureWebpack runs once, but content reloads many times in dev (the TODO in contentHelpers.ts, #10185). So the loader must read from one object that stays stable for the life of the dev server and is refreshed in place. Proposal:

    • core owns a small mutable holder ({sourceToPermalink: Map} + a resolve() helper), created once per loadSite() and reused across reloadSite() / reloadSitePlugin() (both currently rebuild Props; the holder is carried over and refilled after loadPlugins());
    • it is exposed on LoadContext (name to be bikeshedded; context.markdownLinks?), and docs / blog / pages pass it to createMDXLoaderItem() as a new optional siteMarkdownLinks option, next to siteDir and markdownConfig. Plugins that don't pass it get today's behaviour.

    Alternatives I considered and would rather not do: a module-level singleton in @docusaurus/utils keyed by siteDir (works, zero plugin changes, but hidden global state), or attaching the map to the webpack compiler from a core webpack plugin (works, but the loader would depend on an undocumented compiler property).

    Once this exists, the per-plugin mutable contentHelpers maps could be retired in a follow-up (docs/blog/pages would resolve through the same holder, with their own content paths first), which is the cleanup #10185 was asking for. Out of scope for this PR.

    5. Versioned docs

    Keys are the real file paths, so nothing special is needed: ../docs/x.md from a blog post hits docs/x.md (the current version, i.e. /docs/next/x on a versioned site), while ../versioned_docs/version-1.0/x.md hits 1.0. The caveat @slorber raised still applies: a relative link from docs/x.md to ../blog/post.md gets one level deeper when the doc is copied into versioned_docs/version-1.3/. Site-root links (/blog/post.md) and @site/blog/post.md survive versioning, so the docs page will recommend those for cross-plugin links.

    6. i18n

    The map is built per locale build, from the file actually used for each route (translated file when it exists, default file otherwise). A cross-plugin link written against the default-locale path still resolves when the target is not translated, and falls back to onBrokenMarkdownLinks when it is; that link is broken today anyway, so no regression. Registering the default-locale source alongside the translated one is a possible follow-up.

    7. Tests / PR scope

    • @docusaurus/utils: resolveMarkdownLinkPathname with contentPath = siteDir;
    • mdx-loader remark plugin: plugin hit, site-wide fallback hit, both miss → onBrokenMarkdownLinks;
    • core: registry built from routes (multi-instance, versioned, duplicate source);
    • website: cross-plugin links in the dogfood site (docs → blog, blog → docs, pages → docs), plus updating markdown-features-links.mdx, which currently documents the limitation.

    Target size is a few hundred lines, one PR. If you'd prefer the LoadContext addition split out first, I can do that.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugdifficulty: advanceddomain: markdown

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions