Skip to content

Instantly share code, notes, and snippets.

@ryanflorence
Last active March 24, 2025 01:33

Revisions

  1. ryanflorence revised this gist Jan 18, 2023. 1 changed file with 8 additions and 6 deletions.
    14 changes: 8 additions & 6 deletions usage.ts
    Original file line number Diff line number Diff line change
    @@ -1,13 +1,15 @@
    import type { V2_MetaFunction } from "@remix-run/node";
    import { mergeMeta } from "./merge-meta";

    export const meta: V2_MetaFunction = mergeMeta(
    export const meta = mergeMeta(
    // these will override the parent meta
    () => {
    return [{ title: "Heyooooo" }];
    ({ data }) => {
    return [{ title: data.project.name }];
    },

    // these will be appended to the parent meta
    () => {
    ({ matches }) => {
    return [{ name: "author", content: "Ryan Florence" }];
    },
    );
    );

    // both functions get the same arguments as a normal meta function
  2. ryanflorence created this gist Jan 18, 2023.
    38 changes: 38 additions & 0 deletions merge-meta.ts
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,38 @@
    import type { V2_HtmlMetaDescriptor, V2_MetaFunction } from "@remix-run/node";

    export const mergeMeta = (
    overrideFn: V2_MetaFunction,
    appendFn?: V2_MetaFunction,
    ): V2_MetaFunction => {
    return arg => {
    // get meta from parent routes
    let mergedMeta = arg.matches.reduce((acc, match) => {
    return acc.concat(match.meta || []);
    }, [] as V2_HtmlMetaDescriptor[]);

    // replace any parent meta with the same name or property with the override
    let overrides = overrideFn(arg);
    for (let override of overrides) {
    let index = mergedMeta.findIndex(
    meta =>
    ("name" in meta &&
    "name" in override &&
    meta.name === override.name) ||
    ("property" in meta &&
    "property" in override &&
    meta.property === override.property) ||
    ("title" in meta && "title" in override),
    );
    if (index !== -1) {
    mergedMeta.splice(index, 1, override);
    }
    }

    // append any additional meta
    if (appendFn) {
    mergedMeta = mergedMeta.concat(appendFn(arg));
    }

    return mergedMeta;
    };
    };
    13 changes: 13 additions & 0 deletions usage.ts
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,13 @@
    import type { V2_MetaFunction } from "@remix-run/node";
    import { mergeMeta } from "./merge-meta";

    export const meta: V2_MetaFunction = mergeMeta(
    // these will override the parent meta
    () => {
    return [{ title: "Heyooooo" }];
    },
    // these will be appended to the parent meta
    () => {
    return [{ name: "author", content: "Ryan Florence" }];
    },
    );