the complete guide to supabase auth in nuxtjs

introduction to supabase and nuxtjs

building a full stack application requires a robust, secure, and scalable authentication system. as a developer, managing user sessions, password resets, and oauth providers can often feel overwhelming. but don't worry—supabase and nuxtjs make this process incredibly smooth! whether you are a student learning the ropes or an experienced engineer optimizing your devops pipeline, this guide will walk you through everything you need to know.

supabase provides an open-source backend-as-a-service with a powerful authentication engine, while nuxtjs offers a fantastic vue-based framework for building performant web apps. let's dive into the coding part and get auth working seamlessly in your project!

prerequisites

before we start, make sure you have the following ready:

  • a basic understanding of vuejs or nuxtjs.
  • node.js installed on your machine.
  • a free supabase account.

step 1: setting up your nuxtjs project

first, let's create a fresh nuxt application. open your terminal and run the following commands:

npx nuxi@latest init supabase-nuxt-auth
cd supabase-nuxt-auth

this will scaffold a brand-new nuxt 3 project for you. once the installation is complete, we need to install the official supabase module for nuxt.

step 2: installing and configuring the supabase module

the nuxt team provides an official module that handles authentication state, routing, and much more right out of the box. install it via your terminal:

npm install @nuxtjs/supabase

now, add the module to your nuxt.config.ts file. this registers the module and allows you to configure it globally:

export default definenuxtconfig({
  modules: ['@nuxtjs/supabase'],
  supabase: {
    url: process.env.supabase_url,
    key: process.env.supabase_key,
    redirect: false
  }
})

next, create a .env file in the root of your project to securely store your supabase credentials. you can find these values in the api settings of your supabase project dashboard.

supabase_url="https://your-project-ref.supabase.co"
supabase_key="your-anon-public-key"

step 3: building the login page

now for the fun part! let's create a login page using supabase's built-in authentication methods. the @nuxtjs/supabase module provides handy auto-imported composables like usesupabaseclient() and usesupabaseauthclient().

create a file at pages/login.vue:

<template>
  <div class="auth-container">
    <h3>sign in</h3>
    <form @submit.prevent="handlelogin">
      <input v-model="email" type="email" placeholder="email" required />
      <input v-model="password" type="password" placeholder="password" required />
      <button type="submit">log in</button>
    </form>
    <button @click="handleoauthlogin">sign in with github</button>
  </div>
</template>

<script setup>
const email = ref('')
const password = ref('')
const authclient = usesupabaseauthclient()

const handlelogin = async () => {
  const { error } = await authclient.signinwithpassword({
    email: email.value,
    password: password.value,
  })
  if (error) console.error('login error:', error.message)
  else navigateto('/dashboard')
}

const handleoauthlogin = async () => {
  const { error } = await authclient.signinwithoauth({
    provider: 'github',
  })
  if (error) console.error('oauth error:', error.message)
}
</script>

notice how simple that is! you don't need to write complex backend logic. the signinwithpassword and signinwithoauth methods handle the heavy lifting, streamlining your full stack workflow and keeping your codebase clean.

step 4: implementing user registration

registration is just as easy. let's add a signup function. you can modify the same file or create a new pages/register.vue component:

const handlesignup = async () => {
  const { error } = await authclient.signup({
    email: email.value,
    password: password.value,
  })
  if (error) console.error('signup error:', error.message)
  else alert('check your email for the confirmation link!')
}

by default, supabase requires email confirmation. you can toggle this off in your supabase dashboard under authentication settings, but we highly recommend keeping it on for production apps to improve security and seo (ensuring real users are interacting with your site reduces spam and bounce rates).

step 5: protecting your routes (middleware)

in any full stack application, you must protect private routes. if a user isn't logged in, they shouldn't access the dashboard. let's create a middleware file to handle this.

create middleware/auth.ts:

export default definenuxtroutemiddleware((to, from) => {
  const user = usesupabaseuser()
  if (!user.value) {
    return navigateto('/login')
  }
})

to use this middleware, go to your protected page (e.g., pages/dashboard.vue) and add the definepagemeta macro:

<script setup>
definepagemeta({
  middleware: 'auth'
})
</script>

<template>
  <div>
    <h3>welcome to the dashboard!</h3>
    <p>this page is protected.</p>
  </div>
</template>

this is a fundamental concept in coding for the web: ensuring private data stays private. the middleware intercepts the route change and redirects unauthenticated users before they even see the page.

step 6: logging out

to complete the authentication cycle, we need a logout button. inside your dashboard or a navigation component, add the following:

<script setup>
const authclient = usesupabaseauthclient()
const user = usesupabaseuser()

const logout = async () => {
  await authclient.signout()
  navigateto('/login')
}
</script>

<template>
  <button v-if="user" @click="logout">log out</button>
</template>

why this setup matters for your workflow

integrating supabase into nuxtjs drastically reduces the time you spend on devops and backend infrastructure. instead of configuring servers, managing databases, and securing token logic from scratch, you can focus on writing beautiful frontend code and delivering features faster.

additionally, fast, secure websites with personalized content (like user dashboards) tend to have better user retention and lower bounce rates, which indirectly boosts your site's seo performance. search engines love fast, reliable sites!

conclusion

congratulations! you have successfully implemented a complete authentication system in nuxtjs using supabase. you learned how to set up the environment, log users in and out, register new users, and protect private routes using middleware.

remember, building applications is a journey. don't be afraid to experiment with different oauth providers or add features like password reset flows. keep coding, keep learning, and enjoy building amazing full stack applications!

Comments

Discussion

Share your thoughts and join the conversation

Loading comments...

Join the Discussion

Please log in to share your thoughts and engage with the community.