Setting the file. One moment.
Skill 13 · Clerk Nuxt Patterns
Subchapter 13.2
references/nuxt-middleware.mdMarkdown1 KBView on GitHub
Also bundled
Evals@clerk/nuxt auto-registers an auth named middleware. Use it with definePageMeta:
<script setup lang="ts">
definePageMeta({ middleware: 'auth' })
</script>This redirects unauthenticated users to the sign-in page automatically.
Create middleware/require-org.ts for custom logic:
export default defineNuxtRouteMiddleware(() => {
const { isSignedIn, orgId } = useAuth()
if (!isSignedIn.value) {
return navigateTo('/sign-in')
}
if (!orgId.value) {
return navigateTo('/select-org')
}
})Apply to a page:
<script setup lang="ts">
definePageMeta({ middleware: ['auth', 'require-org'] })
</script>For API-level protection in server/middleware/auth.ts:
import { clerkClient } from '@clerk/nuxt/server'
export default defineEventHandler(async (event) => {
const auth = event.context.auth
if (getRequestURL(event).pathname.startsWith('/api/protected')) {
if (!auth?.userId) {
throw createError({ statusCode: 401, message: 'Unauthorized' })
}
}
})Configure in .env:
NUXT_PUBLIC_CLERK_SIGN_IN_URL=/sign-in
NUXT_PUBLIC_CLERK_SIGN_UP_URL=/sign-up
NUXT_PUBLIC_CLERK_SIGN_IN_FALLBACK_REDIRECT_URL=/dashboard
NUXT_PUBLIC_CLERK_SIGN_UP_FALLBACK_REDIRECT_URL=/dashboard