// auth-middleware.ts
export const authEnabledRef = FiberRef.unsafeMake(true);
export const withAuthEnabled = (enabled = true) =>
Layer.locallyScoped(authEnabledRef, enabled);
export const AuthMiddleware = Http.middleware.make((app) =>
Effect.gen(function* ($) {
const request = yield* $(Http.request.ServerRequest);
const isAuthEnabled = yield* $(FiberRef.get(authEnabledRef));
if (!isAuthEnabled) {
return yield* $(app);
}
const isSessionValid: boolean = someCustomLogic(request)
if (!isSessionValid) {
return yield* $(UnauthorizedResponse);
}
return yield* $(app);
}),
);
// router.ts
const PublicRouter = Http.router.empty.pipe(
Http.router.get("/hello", Http.response.json({ data: "Hello Effect Server" })),
Http.router.use(Effect.provide(
withAuthEnabled(false)
)),
);
export const HttpRouterLive = Http.router.empty.pipe(
Http.router.mount("/public", PublicRouter),
Http.router.mount("/app", AppRouter),
Http.router.use(AuthMiddleware),
);
// auth-middleware.ts
export const authEnabledRef = FiberRef.unsafeMake(true);
export const withAuthEnabled = (enabled = true) =>
Layer.locallyScoped(authEnabledRef, enabled);
export const AuthMiddleware = Http.middleware.make((app) =>
Effect.gen(function* ($) {
const request = yield* $(Http.request.ServerRequest);
const isAuthEnabled = yield* $(FiberRef.get(authEnabledRef));
if (!isAuthEnabled) {
return yield* $(app);
}
const isSessionValid: boolean = someCustomLogic(request)
if (!isSessionValid) {
return yield* $(UnauthorizedResponse);
}
return yield* $(app);
}),
);
// router.ts
const PublicRouter = Http.router.empty.pipe(
Http.router.get("/hello", Http.response.json({ data: "Hello Effect Server" })),
Http.router.use(Effect.provide(
withAuthEnabled(false)
)),
);
export const HttpRouterLive = Http.router.empty.pipe(
Http.router.mount("/public", PublicRouter),
Http.router.mount("/app", AppRouter),
Http.router.use(AuthMiddleware),
);