remix-run / remix

Build Better Websites. Create modern, resilient user experiences with web fundamentals.
https://remix.run
MIT License
28.15k stars 2.36k forks source link

cannot import server module in meta #9418

Closed lilouartz closed 3 weeks ago

lilouartz commented 3 weeks ago

Reproduction

https://stackblitz.com/edit/remix-run-remix-feajtw?file=vite.config.ts,app%2Froutes%2Ffoo.server.ts,app%2Froutes%2F_index.tsx

System Info

see repro

Used Package Manager

npm

Expected Behavior

I would expect that I am able to use server utilities in meta because it is executed server side

Actual Behavior

I am unable to use server utilities in meta

lilouartz commented 3 weeks ago

I worked around this by moving all meta data generation to loader and then meta just becomes a dumb function to pass it through.

export const meta: MetaFunction<typeof loader> = ({ data }) => {
  if (!data) {
    return [];
  }

  return data?.meta;
};

and then just abstracted it with:

const createDumbMeta = <T,>(): MetaFunction<T> => {
  return ({ data }) => {
    if (typeof data === 'object' && data !== null && 'meta' in data) {
      return data?.meta as Array<Record<string, unknown>>;
    } else {
      return [];
    }
  };
};

export const meta = createDumbMeta<typeof loader>();

feels like a workaround

sergiodxa commented 3 weeks ago

I would expect that I am able to use server utilities in meta because it is executed server side

The MetaFunction runs both server side and client side, so it's not executed server side only which is why you can't use server modules there.

Moving them to the loader as you did is the correct solution.

lilouartz commented 3 weeks ago

Understood. Thank you!