Authentication on the server

The server side has 1 middleware and 2 helper functions for authentication:

Middleware

The middleware DOES NOT redirect if the user is invalid, it simply sets a context object that looks like:

{
    isAuthenticated: boolean,
    user: User | undefined,
}

If a route requires authentication and you want to access the user object with type-safety, you can call:

export default defineEventHandler(async (event) => {
    const user = getUserOrThrow(event)

    // Use the user object here
    user.email // string
})

If you only want to check if the user is authenticated (and throw a unauthorized error if not), you can call:

export default defineEventHandler(async (event) => {
    requireUser(event)
})

Both these functions ensure that the user exists.