question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

User only available after middleware has run

See original GitHub issue

Version

@nuxtjs/supabase: v0.1.9 nuxt: v3.0.0-rc.1

Steps to reproduce

create global auth guard like this:

export default defineNuxtRouteMiddleware((to) => {
  const user = useSupabaseUser()
  if (!(user.value) && to.name !== 'login')
    return navigateTo('/login')
})

create login page with logic like this



const client = useSupabaseClient()

const user = useSupabaseUser()

const email = ref('')

const signIn = async() => {
  const { session, error } = await client.auth.signIn({ email: email.value })

}

You’ll get a link like this which redirects you to your page with the credentials to setup a Supabase User.

https://pjbhhvurmrikesghutkr.supabase.co/auth/v1/verify?token=myToken&type=magiclink&redirect_to=http://localhost:3000/

What is Expected?

I should be redirected to the url in the redirect_to query param in the link

What is actually happening?

The user is undefined when the authguard is running its logic and therefore the user is redirected to the login page instead of the original destination. The user only becomes available after the navigation has finished, leaving the user on the login page, even though they are logged in. We could watch the user on the login route and redirect, but this seems unnecessary.

Edit:

Also getting this error on the server side when using the link in the email:

[nuxt] [request error] Auth session missing!
  at ./.nuxt/dev/index.mjs:651:13  
  at processTicksAndRejections (node:internal/process/task_queues:96:5)  
  at async ./node_modules/.pnpm/h3@0.7.4/node_modules/h3/dist/index.mjs:417:19  
  at async Server.nodeHandler (./node_modules/.pnpm/h3@0.7.4/node_modules/h3/dist/index.mjs:367:7)

Issue Analytics

  • State:closed
  • Created a year ago
  • Reactions:4
  • Comments:14

github_iconTop GitHub Comments

3reactions
IIFelixcommented, Aug 6, 2022

Using setTimeout fixed it for me.

const signIn = async () => {
  await client.auth.signIn({
    email: email.value,
    password: password.value,
  })
  await new Promise((resolve) => {
    setTimeout(resolve, 50)
  })
  console.log(user.value)

  navigateTo('/')
}
3reactions
mwohlancommented, Apr 22, 2022

Current workaround for me that works with auth protected routes and magic links:

middleware

export default defineNuxtRouteMiddleware((to) => {
  const user = useSupabaseUser()

  if (!(user.value))
    //reroute to login saving the current destination in the redirect query param
    return navigateTo({ name: 'login', query: { redirect: to.path } })
})

plugin to watch route and user

export default defineNuxtPlugin(() => {
  const user = useSupabaseUser()
// globally watch user and route. If a user and a redirect query param exist: 
  watchEffect(() => {
    if (user.value) {
      const route = useRoute()
      if (route.query.redirect)
        navigateTo({ path: route.query.redirect as string })
    }
  })
})

sign in logic on the login page:

const signIn = async() => {
// the redirectTo param is for magic/confirmation links 
  const { session, error } = await client.auth.signIn({ email: email.value }, { redirectTo: `http://localhost:3000${route.query?.redirect}` })
// this is for username + password sign in to trigger the watchEffect. The component doesnt get rerendered afaik
navigateTo({ name: 'login', query: { redirect: route.query.redirect } })
}

It works for both use cases but is also quite hacky.

Read more comments on GitHub >

github_iconTop Results From Across the Web

User only available after middleware has run #28 - GitHub
The user only becomes available after the navigation has finished, leaving the user on the login page, even though they are logged in....
Read more >
Use specific middleware in Express for all paths except a ...
I would add checkUser middleware to all my paths, except homepage. app.get('/', routes.index); app.get('/account', checkUser, routes.account);.
Read more >
Conditional Middleware based on request in ASP.NET Core
This post looks at how to configure ASP.NET Core middleware in a way that allows you to have different middleware for different types...
Read more >
ASP.NET Core Middleware | Microsoft Learn
If another Use or Run delegate is added after the Run delegate, ... File Middleware, including those under wwwroot, are publicly available.
Read more >
Middleware - Laravel - The PHP Framework For Web Artisans
For example, Laravel includes a middleware that verifies the user of your application is authenticated. If the user is not authenticated, the middleware...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found