Adesh
Adesh
HHono
Created by Adesh on 1/22/2025 in #help
Get `auth` session when API endpoint is called from a server component
Thank you so much for your time and efforts, really appreciate it 🤗
77 replies
HHono
Created by Adesh on 1/22/2025 in #help
Get `auth` session when API endpoint is called from a server component
I am directly querying the db
77 replies
HHono
Created by Adesh on 1/22/2025 in #help
Get `auth` session when API endpoint is called from a server component
@ambergristle got it, Sorry for the misconception, queryFn can be different. This does the trick
const queryClient = new QueryClient()
await queryClient.prefetchQuery({
queryKey: ['posts'],
queryFn: async () => {
const posts = await db.query.posts.findMany({})
return posts
},
staleTime: 10 * 1000,
})
const queryClient = new QueryClient()
await queryClient.prefetchQuery({
queryKey: ['posts'],
queryFn: async () => {
const posts = await db.query.posts.findMany({})
return posts
},
staleTime: 10 * 1000,
})
77 replies
HHono
Created by Adesh on 1/22/2025 in #help
Get `auth` session when API endpoint is called from a server component
Ohk, let me try
77 replies
HHono
Created by Adesh on 1/22/2025 in #help
Get `auth` session when API endpoint is called from a server component
But for the first call which was from the server component, it is null
77 replies
HHono
Created by Adesh on 1/22/2025 in #help
Get `auth` session when API endpoint is called from a server component
hmm, we do have the cookies there authjs.session-token=7454b460-84ba-40fb-b42e-773e7ec14b71; authjs.csrf-token=3955a742945c7d4e5eba846e96d95ed7621e1b31bde38156591bf59d29e73888%7C7c07efc9cd83ae19ede691973019d08973f2b0ab079c68f0a2e53712db45445c; authjs.callback-url=http%3A%2F%2Flocalhost%3A3000%2Fposts
77 replies
HHono
Created by Adesh on 1/22/2025 in #help
Get `auth` session when API endpoint is called from a server component
It is a really long trail of logs
77 replies
HHono
Created by Adesh on 1/22/2025 in #help
Get `auth` session when API endpoint is called from a server component
export async function getPosts(): Promise<
Array<Zod.infer<typeof selectPostSchema>>
> {
// const response = await fetch('/api/posts')
const response = await client.api.posts.$get()

if (!response.ok) {
throw new Error(`Request failed with status: ${response.status}`)
}

return response.json()
}
export async function getPosts(): Promise<
Array<Zod.infer<typeof selectPostSchema>>
> {
// const response = await fetch('/api/posts')
const response = await client.api.posts.$get()

if (!response.ok) {
throw new Error(`Request failed with status: ${response.status}`)
}

return response.json()
}
77 replies
HHono
Created by Adesh on 1/22/2025 in #help
Get `auth` session when API endpoint is called from a server component
There is a way to fetch the data directly and pass the result to the client component cache as initial data, But that only works for statically rendered pages
77 replies
HHono
Created by Adesh on 1/22/2025 in #help
Get `auth` session when API endpoint is called from a server component
Yeah, I would have, but the for the react query cache to used, by the client, We need to call the same queryFn and with same queryKey at both the places.
77 replies
HHono
Created by Adesh on 1/22/2025 in #help
Get `auth` session when API endpoint is called from a server component
I'll keep looking for solutions though, I'll update here if something works
77 replies
HHono
Created by Adesh on 1/22/2025 in #help
Get `auth` session when API endpoint is called from a server component
Yeah it is just an optimization, for better UX.
77 replies
HHono
Created by Adesh on 1/22/2025 in #help
Get `auth` session when API endpoint is called from a server component
Yeah
77 replies
HHono
Created by Adesh on 1/22/2025 in #help
Get `auth` session when API endpoint is called from a server component
Just tried it, but still the same
77 replies
HHono
Created by Adesh on 1/22/2025 in #help
Get `auth` session when API endpoint is called from a server component
77 replies
HHono
Created by Adesh on 1/22/2025 in #help
Get `auth` session when API endpoint is called from a server component
Next.js has api routes that runs on the same port, I am hijacking, that to use hono instead
77 replies
HHono
Created by Adesh on 1/22/2025 in #help
Get `auth` session when API endpoint is called from a server component
This is telling next-auth to extend the session to include the user id as well, by default it doesn't https://authjs.dev/guides/extending-the-session
77 replies
HHono
Created by Adesh on 1/22/2025 in #help
Get `auth` session when API endpoint is called from a server component
No I have a catch all api route
import provider from '@/auth.config'
import posts from '@/server/posts'
import { AuthConfig, initAuthConfig } from '@hono/auth-js'
import { Hono } from 'hono'
import { handle } from 'hono/vercel'

export const runtime = 'edge'

const app = new Hono().basePath('/api')

app.use('*', initAuthConfig(getAuthConfig))

// eslint-disable-next-line @typescript-eslint/no-unused-vars
const route = app.route('/posts', posts)

export const GET = handle(app)
export const POST = handle(app)
export const PUT = handle(app)
export const PATCH = handle(app)
export const DELETE = handle(app)

function getAuthConfig(): AuthConfig {
return {
secret: process.env.AUTH_SECRET,
...provider,
}
}

// this export will be used by the RPC client
export type AppType = typeof route
import provider from '@/auth.config'
import posts from '@/server/posts'
import { AuthConfig, initAuthConfig } from '@hono/auth-js'
import { Hono } from 'hono'
import { handle } from 'hono/vercel'

export const runtime = 'edge'

const app = new Hono().basePath('/api')

app.use('*', initAuthConfig(getAuthConfig))

// eslint-disable-next-line @typescript-eslint/no-unused-vars
const route = app.route('/posts', posts)

export const GET = handle(app)
export const POST = handle(app)
export const PUT = handle(app)
export const PATCH = handle(app)
export const DELETE = handle(app)

function getAuthConfig(): AuthConfig {
return {
secret: process.env.AUTH_SECRET,
...provider,
}
}

// this export will be used by the RPC client
export type AppType = typeof route
77 replies
HHono
Created by Adesh on 1/22/2025 in #help
Get `auth` session when API endpoint is called from a server component
I get the session here
const Posts = async () => {
const session = await auth()

if (!session?.user) {
return <Unauthorized />
}

const queryClient = new QueryClient()
await queryClient.prefetchQuery(getPostQueryOptions)

return (
<>
<Toaster />
<h1 className="scroll-m-20 text-4xl font-extrabold tracking-tight lg:text-5xl">
Posts
</h1>
<HydrationBoundary state={dehydrate(queryClient)}>
<PostList />
</HydrationBoundary>
<div>
<CreatePostForm userId={session?.user.id || ''} />
</div>
</>
)
}
const Posts = async () => {
const session = await auth()

if (!session?.user) {
return <Unauthorized />
}

const queryClient = new QueryClient()
await queryClient.prefetchQuery(getPostQueryOptions)

return (
<>
<Toaster />
<h1 className="scroll-m-20 text-4xl font-extrabold tracking-tight lg:text-5xl">
Posts
</h1>
<HydrationBoundary state={dehydrate(queryClient)}>
<PostList />
</HydrationBoundary>
<div>
<CreatePostForm userId={session?.user.id || ''} />
</div>
</>
)
}
But not here
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)
})
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)
})
77 replies
HHono
Created by Adesh on 1/22/2025 in #help
Get `auth` session when API endpoint is called from a server component
The session check in the server component to validate if the page should render or not. But the session check for the api is for when someone hits the backend endpoint from say postman, (It is here where it is not workgin)
77 replies