I have session, but get unautherized error from auth.api.polar or something similar

export const validateApiKey = async (c: Context, next: () => Promise<void>) => {
const apiKey = c.req.header("x-api-key");
const session = await auth.api.getSession({ headers: c.req.raw.headers });

console.log(session, "session");
if (!session) {
c.set("user", null);
c.set("session", null);
return next();
}

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

if (!apiKey) {
return c.json({ error: "API key is required" }, 401);
}

try {
const { valid, error, key } = await auth.api.verifyApiKey({
body: {
key: apiKey,
},
});
if (error) {
console.error("API key verification error:", error);
return c.json({ error: error.message }, 500);
}

if (!valid) {
return c.json({ error: "Invalid or inactive API key" }, 401);
}

// Add user data to context for use in handlers
c.set("userId", key?.userId);
c.set("apiKey", apiKey);

await next();
} catch (error) {
console.error("Error validating API key:", error);
return c.json({ error: "Internal server error" }, 500);
}
};
export const validateApiKey = async (c: Context, next: () => Promise<void>) => {
const apiKey = c.req.header("x-api-key");
const session = await auth.api.getSession({ headers: c.req.raw.headers });

console.log(session, "session");
if (!session) {
c.set("user", null);
c.set("session", null);
return next();
}

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

if (!apiKey) {
return c.json({ error: "API key is required" }, 401);
}

try {
const { valid, error, key } = await auth.api.verifyApiKey({
body: {
key: apiKey,
},
});
if (error) {
console.error("API key verification error:", error);
return c.json({ error: error.message }, 500);
}

if (!valid) {
return c.json({ error: "Invalid or inactive API key" }, 401);
}

// Add user data to context for use in handlers
c.set("userId", key?.userId);
c.set("apiKey", apiKey);

await next();
} catch (error) {
console.error("Error validating API key:", error);
return c.json({ error: "Internal server error" }, 500);
}
};
I get valid session here
export const scheduleRouter = new Hono<{ Variables: Variables }>()
.use("*", validateApiKey)
.post("/", validateBody(scheduleUrlSchema), async (c) => {
const user = c.get("user");
const session = c.get("session");
const apiKey = c.get("apiKey");
const urlRequest = c.get("validatedBody") as ScheduleUrlRequest;

try {
const meters = await auth.api
.meters({
query: {
limit: 1,
},
})
.catch((error) => {
console.error("Error fetching meters:", error);
return { result: { items: [] } }; // Return empty if error occurs
});
const meter = meters.result.items[0];
if (!meter || meter.balance === 0) {
return c.json({ error: "Insufficient credits" }, 402);
}
export const scheduleRouter = new Hono<{ Variables: Variables }>()
.use("*", validateApiKey)
.post("/", validateBody(scheduleUrlSchema), async (c) => {
const user = c.get("user");
const session = c.get("session");
const apiKey = c.get("apiKey");
const urlRequest = c.get("validatedBody") as ScheduleUrlRequest;

try {
const meters = await auth.api
.meters({
query: {
limit: 1,
},
})
.catch((error) => {
console.error("Error fetching meters:", error);
return { result: { items: [] } }; // Return empty if error occurs
});
const meter = meters.result.items[0];
if (!meter || meter.balance === 0) {
return c.json({ error: "Insufficient credits" }, 402);
}
I get unautehrized error over here
Solution:
fixed it ``` const meters = await auth.api.meters({ query: {...
Jump to solution
3 Replies
whizzy
whizzyOP3mo ago
export const auth = betterAuth({
database: drizzleAdapter(db, {
provider: "pg",
}),
logger: {
level: "info",
},
socialProviders: {
google: {
clientId: Resource.GOOGLE_CLIENT_ID.value,
clientSecret: Resource.GOOGLE_CLIENT_SECRET.value,
},
},
plugins: [
apiKey({
apiKeyHeaders: ["x-api-key"],
}),
polar({
client: polarClient,
createCustomerOnSignUp: true,
use: [
checkout({
products: [
{
productId: "08a8582e-c70b-4a00-b962-f9cf91460a68", // ID of Product from Polar Dashboard
slug: "credits", // Custom slug for easy reference in Checkout URL, e.g. /checkout/credits
},
],
}),
portal(),
usage(),
// webhooks({
// secret: process.env.POLAR_WEBHOOK_SECRET!,
// }),
],
}),
nextCookies(),
],
advanced: {
defaultCookieAttributes: {
sameSite: "none",
secure: true,
partitioned: true, // New browser standards will mandate this for foreign cookies
},
},
});
export const auth = betterAuth({
database: drizzleAdapter(db, {
provider: "pg",
}),
logger: {
level: "info",
},
socialProviders: {
google: {
clientId: Resource.GOOGLE_CLIENT_ID.value,
clientSecret: Resource.GOOGLE_CLIENT_SECRET.value,
},
},
plugins: [
apiKey({
apiKeyHeaders: ["x-api-key"],
}),
polar({
client: polarClient,
createCustomerOnSignUp: true,
use: [
checkout({
products: [
{
productId: "08a8582e-c70b-4a00-b962-f9cf91460a68", // ID of Product from Polar Dashboard
slug: "credits", // Custom slug for easy reference in Checkout URL, e.g. /checkout/credits
},
],
}),
portal(),
usage(),
// webhooks({
// secret: process.env.POLAR_WEBHOOK_SECRET!,
// }),
],
}),
nextCookies(),
],
advanced: {
defaultCookieAttributes: {
sameSite: "none",
secure: true,
partitioned: true, // New browser standards will mandate this for foreign cookies
},
},
});
this is my auth
Ping
Ping3mo ago
You may want to open an issue on Polars github if it relates to Polar.
Solution
whizzy
whizzy3mo ago
fixed it
const meters = await auth.api.meters({
query: {
limit: 1,
},
headers: c.req.raw.headers,
});
const meters = await auth.api.meters({
query: {
limit: 1,
},
headers: c.req.raw.headers,
});
jut had to add headers

Did you find this page helpful?