Hi, I'm building a backend with hono and better-auth, since better auth needs a DB I can only pass t

Hi, I'm building a backend with hono and better-auth, since better auth needs a DB I can only pass the DB instance using I middleware so I wonder if it is ok I initialize better auth only once in cloudflare worker, I mean to create a singleton that lives as long as the worker do. here is an example:

export class Auth {
  static initialized = false;
  private static instance: ReturnType<typeof betterAuth>;

  static async init(c: Context<Env>) {
    if (Auth.instance) {
      await Auth.getSession(c);
      Auth.initialized = true;
      return Object.freeze(Auth.instance);
    }

    Auth.instance = betterAuth({
      database: drizzleAdapter(
        {
          dialect: new D1Dialect({
            database: c.env.DB,
          }),
        },
      ),
    });

    Auth.initialized = true;

    await Auth.getSession(c);

    return Object.freeze(Auth.instance);
  }

  static async getSession(c: Context) {
    const session = await Auth.instance.api.getSession({
      headers: c.req.raw.headers,
    });

    c.set("user", session?.user ?? null);
    c.set("session", session?.session ?? null);

    return session;
  }

  static getInstance() {
    if (!Auth.instance) {
      throw new Error("Auth instance not initialized");
    }

    return Object.freeze(Auth.instance);
  }
}

and in the worker handler:

const app = new Hono<Env>();

app.use("*", async (c, next) => {
  if (Auth.initialized) return next();

  await Auth.init(c);
  return next();
});

app.all("/api/**", (c) => Auth.getInstance().handler(c.req.raw));

export default app;
export type ApiRoutes = typeof apiRoutes;

The rational behind this approach is to not reinitialize the auth instance and make a db connection for each request
Was this page helpful?