Description
I created a new Nuxt project and followed the nuxt-auth-utils example here: https://nuxt.com/docs/guide/recipes/sessions-and-authentication
However, the login does not work. loggedIn.value
is always false. I am a software engineer but I am not super versed web / node.js / Nuxt, so I am not really sure what to look at. Both the terminal (running the dev environment) nor the web console in the browser show any sort of error logs.
I am running Nuxt 3.15.3 with Nitro 2.10.4.
Here is what I have:
login.post.ts:
import { z } from 'zod'
const bodySchema = z.object({
email: z.string().email(),
password: z.string().min(8)
})
export default defineEventHandler(async (event) => {
const { email, password } = await readValidatedBody(event, bodySchema.parse)
if (email === 'test' && password === 'test') {
// side question: shouldn't this be replaceUserSession to make sure it doesn't accidentally merge multiple user sessions together?
await setUserSession(event, {
user: {
name: 'John Doe'
}
})
return {}
}
throw createError({
statusCode: 401,
message: 'Bad credentials'
})
})
login.vue:
<script setup lang="ts">
const { loggedIn, user, fetch: refreshSession } = useUserSession()
const credentials = reactive({
email: '',
password: '',
})
async function login() {
$fetch('/api/login', {
method: 'POST',
body: credentials
})
.then(async () => {
await refreshSession()
await navigateTo('/')
})
.catch(() => alert('Bad credentials'))
}
</script>
<template>
<h1>Login</h1>
<form @submit.prevent="login">
<input v-model="credentials.email" type="email" placeholder="Email" />
<input v-model="credentials.password" type="password" placeholder="Password" />
<button type="submit">Login</button>
</form>
</template>
This part gets called because if I enter anything other than test & test in may login sheet, I see an alert 'Bad credentials'.
However after login, I immediately get forwarded to the login page again and if I manually go to /
I also get forwarded to the login page. Here is my middleware and my home page:
middleware/authenticated.ts:
export default defineNuxtRouteMiddleware(() => {
const { loggedIn } = useUserSession()
if (!loggedIn.value) {
return navigateTo('/login')
}
})
index.vue:
<script setup lang="ts">
definePageMeta({
middleware: ['authenticated'],
})
const { user, clear: clearSession } = useUserSession()
async function logout() {
await clearSession()
await navigateTo('/login')
}
</script>
<template>
<div>
<h1>Welcome Agent {{ user.name }}</h1>
<button @click="logout">Logout</button>
</div>
</template>
As you can see, this is all pretty much exactly from the guide, but for some reason I keep landing on the login page and if I add a console log for the loggedIn.value or for user it logs false and null respectively.
Any ideas what I am missing or how to debug this further? This was supposed to be a little weekend project but it seems I'm already struggling with the basics.