Session Access and Route Protection
On the server side you can get access to the current session like this:
import { getServerSession } from '#auth'
export default eventHandler(async (event) => {
const session = await getServerSession(event)
})
This is inspired by the getServerSession
of NextAuth.js. It also avoids an external HTTP GET
request to the /api/auth/sessions
endpoint, instead directly calling a pure JS-method.
Note:
If you use Nuxt's useFetch
from your app-components to fetch data from an endpoint that uses getServerSession
or getToken
you will need to manually pass along cookies as Nuxt 3 universal rendering will not do this per-default when it runs on the server-side. Not passing along cookies will result in getServerSession
returning null
when it is called from the server-side as no auth cookies will exist. Here's an example that manually passes along cookies:
const headers = useRequestHeaders(['cookie']) as HeadersInit
const { data: token } = await useFetch('/api/token', { headers })
Endpoint Protection
To protect an endpoint, check the session after fetching it:
// file: ~/server/api/protected.get.ts
import { getServerSession } from '#auth'
export default eventHandler(async (event) => {
const session = await getServerSession(event)
if (!session) {
return { status: 'unauthenticated!' }
}
return { status: 'authenticated!' }
})
Server Middleware
You can also use this in a Nuxt server middleware to protect multiple pages at once and keep the authentication logic out of your endpoints:
// file: ~/server/middleware/auth.ts
import { getServerSession } from '#auth'
export default eventHandler(async (event) => {
const session = await getServerSession(event)
if (!session) {
throw createError({
statusMessage: 'Unauthenticated',
statusCode: 403
})
}
})