Adesh
Adesh
HHono
Created by Adesh on 1/22/2025 in #help
Get `auth` session when API endpoint is called from a server component
import { Hono } from 'hono'
import { verifyAuth } from '@hono/auth-js'
import { zValidator } from '@hono/zod-validator'
import { db } from '@/db'
import { insertPostSchema, posts } from '@/db/schema'
import { auth } from '@/auth'

const app = new Hono()
// Protect API for authenticated users only
.get('/', async (c) => {
// Get the session manually instead of using middleware
const session = await auth()

// Check authentication
if (!session?.user) {
return c.json({ error: 'Unauthorized' }, 401)
}

const posts = await db.query.posts.findMany({})
return c.json(posts)
})
import { Hono } from 'hono'
import { verifyAuth } from '@hono/auth-js'
import { zValidator } from '@hono/zod-validator'
import { db } from '@/db'
import { insertPostSchema, posts } from '@/db/schema'
import { auth } from '@/auth'

const app = new Hono()
// Protect API for authenticated users only
.get('/', async (c) => {
// Get the session manually instead of using middleware
const session = await auth()

// Check authentication
if (!session?.user) {
return c.json({ error: 'Unauthorized' }, 401)
}

const posts = await db.query.posts.findMany({})
return c.json(posts)
})
The session is undefined when the route is called from the server component, but I get the value when I call it from the client component
77 replies