javascriptreactjsremixremix.run

React remix middleware and database connection


I am facing a problem that is Remix doesn't have a middleware before a loader function. In Express we have middlewares to authenticate a user. I am calling isAuth function in every loader and action function for authenticating.

export let loader = async ({ request }) => {
  await isAuth(request);
  const users = await getAllUsers();

  return json({ users }, { status: 200 });
};

and also I am connecting my database in every utility function.

export const getAllUsers = async () => {
  await dbconnect();
  return await User.find();
};

export const getUser = async (id) => {
  await dbconnect();
  return await User.findById(id);
};

So is there a better way of doing it?


Solution

  • Yes, currently Remix does not have middleware, so you will need to authenticate users in each loader. Although middleware is coming soon.

    https://github.com/remix-run/remix/discussions/7642

    As for database connections, you should be able to reuse the connection by exporting it from another file.

    See the Connect to the database section of the Remix Jokes tutorial for an example.

    https://remix.run/docs/en/main/tutorials/jokes#connect-to-the-database