Hono and Better-Auth
Hi there,
I know this is the better-auth thing, but just asking for a help.
This is my
This is my Hono root route:
This is my Hono middleware:
This is auth client from
This is
But I am getting
I can do sign-in and sign-out, but I am just getting authorized when I use
I know this is the better-auth thing, but just asking for a help.
This is my
authauth from apiapi:import { betterAuth } from "better-auth";
import { drizzleAdapter } from "better-auth/adapters/drizzle";
import { db } from "../db";
import { account, session, user, verification } from "../db/schemas/auth-table";
import {
FRONTEND_URL,
GOOGLE_CLIENT_DEV_ID,
GOOGLE_CLIENT_DEV_SECRET,
GOOGLE_CLIENT_PROD_ID,
GOOGLE_CLIENT_PROD_SECRET,
NODE_ENV
} from "../env";
const isProd = NODE_ENV === "production";
export const auth = betterAuth({
socialProviders: {
google: {
clientId: isProd ? GOOGLE_CLIENT_PROD_ID : GOOGLE_CLIENT_DEV_ID,
clientSecret: isProd ? GOOGLE_CLIENT_PROD_SECRET : GOOGLE_CLIENT_DEV_SECRET
}
},
database: drizzleAdapter(db, {
provider: "pg",
schema: { user, session, account, verification }
}),
session: {
expiresIn: 60 * 60 * 24 * 30,
freshAge: 60 * 60 * 24 * 1
},
trustedOrigins: [FRONTEND_URL]
});import { betterAuth } from "better-auth";
import { drizzleAdapter } from "better-auth/adapters/drizzle";
import { db } from "../db";
import { account, session, user, verification } from "../db/schemas/auth-table";
import {
FRONTEND_URL,
GOOGLE_CLIENT_DEV_ID,
GOOGLE_CLIENT_DEV_SECRET,
GOOGLE_CLIENT_PROD_ID,
GOOGLE_CLIENT_PROD_SECRET,
NODE_ENV
} from "../env";
const isProd = NODE_ENV === "production";
export const auth = betterAuth({
socialProviders: {
google: {
clientId: isProd ? GOOGLE_CLIENT_PROD_ID : GOOGLE_CLIENT_DEV_ID,
clientSecret: isProd ? GOOGLE_CLIENT_PROD_SECRET : GOOGLE_CLIENT_DEV_SECRET
}
},
database: drizzleAdapter(db, {
provider: "pg",
schema: { user, session, account, verification }
}),
session: {
expiresIn: 60 * 60 * 24 * 30,
freshAge: 60 * 60 * 24 * 1
},
trustedOrigins: [FRONTEND_URL]
});This is my Hono root route:
const app = new Hono<Context>().basePath("/api");
app.use(
"*",
cors({
origin: [FRONTEND_URL],
allowHeaders: ["Content-Type", "Authorization"],
allowMethods: ["POST", "GET", "OPTIONS"],
exposeHeaders: ["Content-Length"],
maxAge: 600,
credentials: true
})
);
app.on(["POST", "GET"], "/auth/**", (c) => auth.handler(c.req.raw));
app.route("/authorize", authroize);const app = new Hono<Context>().basePath("/api");
app.use(
"*",
cors({
origin: [FRONTEND_URL],
allowHeaders: ["Content-Type", "Authorization"],
allowMethods: ["POST", "GET", "OPTIONS"],
exposeHeaders: ["Content-Length"],
maxAge: 600,
credentials: true
})
);
app.on(["POST", "GET"], "/auth/**", (c) => auth.handler(c.req.raw));
app.route("/authorize", authroize);This is my Hono middleware:
import { createMiddleware } from "hono/factory";
import { auth } from "../../libs/auth";
import type { ErrorResponse } from "../../libs/types";
import type { Context } from "../context";
export const loggedIn = createMiddleware<Context>(async (c, next) => {
const session = await auth.api.getSession({ headers: c.req.raw.headers });
if (!session) {
return c.json<ErrorResponse>({ success: false, message: "Unauthorized" }, 401);
}
c.set("user", session.user);
c.set("session", session.session);
await next();
});import { createMiddleware } from "hono/factory";
import { auth } from "../../libs/auth";
import type { ErrorResponse } from "../../libs/types";
import type { Context } from "../context";
export const loggedIn = createMiddleware<Context>(async (c, next) => {
const session = await auth.api.getSession({ headers: c.req.raw.headers });
if (!session) {
return c.json<ErrorResponse>({ success: false, message: "Unauthorized" }, 401);
}
c.set("user", session.user);
c.set("session", session.session);
await next();
});This is auth client from
webweb:import { PUBLIC_API } from "$env/static/public";
import { createAuthClient } from "better-auth/svelte";
export const authClient = createAuthClient({ baseURL: `${PUBLIC_API}/auth` });import { PUBLIC_API } from "$env/static/public";
import { createAuthClient } from "better-auth/svelte";
export const authClient = createAuthClient({ baseURL: `${PUBLIC_API}/auth` });This is
requireAuthrequireAuth function to use in +page.server.ts+page.server.ts:export async function requireAuth() {
const res = await fetch(`${PUBLIC_API}/authorize/current`, {
method: "POST",
credentials: "include"
});
if (!res.ok) {
console.error("Failed to authorize", res);
throw new Error("Unauthorized from web");
}
const json = (await res.json()) as SuccessResponse<SuccessType>;
const data = {
session: json.data.session,
user: json.data.user
};
const user = data.user;
console.log("data user", user);
}export async function requireAuth() {
const res = await fetch(`${PUBLIC_API}/authorize/current`, {
method: "POST",
credentials: "include"
});
if (!res.ok) {
console.error("Failed to authorize", res);
throw new Error("Unauthorized from web");
}
const json = (await res.json()) as SuccessResponse<SuccessType>;
const data = {
session: json.data.session,
user: json.data.user
};
const user = data.user;
console.log("data user", user);
}But I am getting
UnauthorizedUnauthorized responsive back although I successfully logged in.I can do sign-in and sign-out, but I am just getting authorized when I use
loggedInloggedIn middelware. How can I fix that?