How to use const session = c.get("session") and const user = c.get("user") in Hono when routes?
Hi everyone, I'm using Hono but the only way I can retrieve c.get("user") is if I export my app variables type?
Is there a more elegant way to do this? Maybe export the "whole app" in each route instead of just variables?
index.ts:
example of a route (thread.ts):
Is there a more elegant way to do this? Maybe export the "whole app" in each route instead of just variables?
index.ts:
// Define app variables type to be used across routes
export type AppVariables = {
user: typeof auth.$Infer.Session.user | null;
session: typeof auth.$Infer.Session.session | null;
};
// Initialize Hono app
const app = new Hono<{
Variables: AppVariables;
}>();
// Auth routes with Better-Auth
app.on(["POST", "GET"], "/api/auth/*", (c) => {
return auth.handler(c.req.raw);
});
// Middlewares
app.use("/api/auth/*", corsMiddleware);
app.use("*", sessionMiddleware, logger(), prettyJSON());
// eslint-disable-next-line @typescript-eslint/no-unused-vars
const routes = app.basePath("/api").route("/threads", threads);
export type AppType = typeof routes;
// Serve static files
app.get("*", serveStatic({ root: "./frontend/dist" }));
app.get("*", serveStatic({ path: "./frontend/dist/index.html" }));
// Export the app with server configuration
export default {
port: process.env["PORT"] || 3000,
hostname: "0.0.0.0",
fetch: app.fetch,
};// Define app variables type to be used across routes
export type AppVariables = {
user: typeof auth.$Infer.Session.user | null;
session: typeof auth.$Infer.Session.session | null;
};
// Initialize Hono app
const app = new Hono<{
Variables: AppVariables;
}>();
// Auth routes with Better-Auth
app.on(["POST", "GET"], "/api/auth/*", (c) => {
return auth.handler(c.req.raw);
});
// Middlewares
app.use("/api/auth/*", corsMiddleware);
app.use("*", sessionMiddleware, logger(), prettyJSON());
// eslint-disable-next-line @typescript-eslint/no-unused-vars
const routes = app.basePath("/api").route("/threads", threads);
export type AppType = typeof routes;
// Serve static files
app.get("*", serveStatic({ root: "./frontend/dist" }));
app.get("*", serveStatic({ path: "./frontend/dist/index.html" }));
// Export the app with server configuration
export default {
port: process.env["PORT"] || 3000,
hostname: "0.0.0.0",
fetch: app.fetch,
};example of a route (thread.ts):
const app = new Hono<{ Variables: AppVariables }>()
.use("/*", rateLimitMiddleware)
.post("/", zValidator("json", searchRequestSchema), async (c) => {
const user = c.get("user");
if (!user) {
return c.json({ error: "Unauthorized" }, 401);
}
...const app = new Hono<{ Variables: AppVariables }>()
.use("/*", rateLimitMiddleware)
.post("/", zValidator("json", searchRequestSchema), async (c) => {
const user = c.get("user");
if (!user) {
return c.json({ error: "Unauthorized" }, 401);
}
...