Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Basic example does not work on fresh install #329

Open
michaelochs opened this issue Jan 26, 2025 · 2 comments
Open

Basic example does not work on fresh install #329

michaelochs opened this issue Jan 26, 2025 · 2 comments
Labels
question Further information is requested

Comments

@michaelochs
Copy link

michaelochs commented Jan 26, 2025

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.

@atinux
Copy link
Owner

atinux commented Jan 27, 2025

Where do you test your project @michaelochs ? locally?

I made a reproduction on https://codesandbox.io/p/devbox/p9z89j using the tutorial from nuxt.com

If you open the preview on the right, it won't work (I guess a cookie policy inside the iframe).

But if you open https://p9z89j-3000.csb.app/, you should be able to login properly

@atinux atinux added the question Further information is requested label Jan 27, 2025
@BITRU
Copy link

BITRU commented Jan 29, 2025

I am having the same issue.
When developing on remote server and access app via serverIP:3000, session is empty, after login.
When use visual-studio code port mapping to open app as localhost:3000 all is working.

when build and run js, session is missing.

@sidebase/nuxt-auth works as expected, but i would like to use this light module.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
question Further information is requested
Projects
None yet
Development

No branches or pull requests

3 participants