Skip to content

How to Build a SaaS with Nuxt 4, better-auth, and Polar

Nuxt 4better-authPolar
How I wire up authentication with better-auth and payments with Polar in a Nuxt 4 SaaS, with the real code from my products.
Michael Hoffmann

Michael Hoffmann

Founder of Nuxt Starter Kit

Three connected tiles labeled better-auth, polar and your app, linked by arrows

Every SaaS I built in the last years started with the same week of work. CodeSnap, Sigxel and Aiduko are very different products, but each of them needed sign-up, sign-in, a paid plan and a protected app area before I could write the first real feature.

In this article, I want to show you how I set up these parts today with Nuxt 4, better-auth and Polar. The code comes from my Nuxt Starter Kit, the foundation I extracted from these products.

What Every SaaS Needs First

Before the product itself, my apps need these five things:

  1. Users who can sign up and sign in
  2. A paid plan (a subscription or a lifetime deal)
  3. A protected app area
  4. An admin area to help users and to block abuse
  5. A deployment that doesn't lock me into one host

Everything else depends on the product. Let's take a look at the first three, as they need the most care.

Authentication With better-auth

better-auth handles sessions, email and password, social login and passkeys. It stores everything in my PostgreSQL database through Drizzle ORM, so I don't depend on a hosted auth service.

Here is a shortened version of my auth setup:

server/utils/auth.ts
import { passkey } from '@better-auth/passkey'
import { betterAuth } from 'better-auth'
import { drizzleAdapter } from 'better-auth/adapters/drizzle'
import { admin, lastLoginMethod } from 'better-auth/plugins'

import * as schema from '../db/schema'

import { setupPolar } from './polar'

export function createBetterAuth () {
  const runtimeConfig = useRuntimeConfig()
  const { sendPasswordResetEmail, sendVerificationEmail } = useEmail()

  return betterAuth({
    baseURL: runtimeConfig.public.baseUrl!,
    database: drizzleAdapter(useDb(), { provider: 'pg', schema }),
    emailAndPassword: {
      enabled: true,
      requireEmailVerification: true,
      sendResetPassword: async ({ url, user }) => {
        await sendPasswordResetEmail(user.name, user.email, url)
      },
    },
    emailVerification: {
      autoSignInAfterVerification: true,
      sendOnSignUp: true,
      sendVerificationEmail: async ({ url, user }) => {
        await sendVerificationEmail(user.name, user.email, url)
      },
    },
    plugins: [
      admin(),
      lastLoginMethod(),
      setupPolar(runtimeConfig.private.polarAccessToken, runtimeConfig.private.polarServer as 'production' | 'sandbox'),
      passkey(),
    ],
    secret: runtimeConfig.betterAuthSecret,
    socialProviders: {
      github: {
        clientId: runtimeConfig.private.githubClientId!,
        clientSecret: runtimeConfig.private.githubClientSecret!,
      },
      google: {
        clientId: runtimeConfig.private.googleClientId!,
        clientSecret: runtimeConfig.private.googleClientSecret!,
      },
    },
  })
}

Let's analyze the above code:

  • requireEmailVerification blocks sign-in until the user clicks the link in the verification email. autoSignInAfterVerification signs them in right after that click, so they don't have to type their password again.
  • The password reset and verification emails go through my own useEmail() composable. better-auth only gives me the URL.
  • The admin() plugin adds roles, bans and impersonation. I need these the first time a user writes to support.
  • passkey() adds passkey sign-in, and GitHub and Google cover social login.

better-auth needs one catch-all server route that forwards all /api/auth/* requests:

server/api/auth/[...all].ts
export default defineEventHandler((event) => {
  const serverAuth = useServerAuth()
  return serverAuth.handler(toWebRequest(event))
})

useServerAuth() creates the better-auth instance on the first request and reuses it afterward.

Protecting Server Routes

A working login page doesn't mean your app is protected. Every server route that returns user data must check the session itself. For that, I use a small helper:

server/utils/auth.ts
export async function requireAuth (event: H3Event) {
  const session = await getAuthSession(event)
  if (!session || !session.user) {
    throw createError({
      statusCode: 401,
      statusMessage: 'Unauthorized',
    })
  }
  event.context.user = session.user
  return session.user as User
}

Now, a protected route is one line at the top of the handler:

server/api/protected.get.ts
export default defineEventHandler(async (event) => {
  const user = await requireAuth(event)
  return { message: `Hello ${user.name}!` }
})

For the admin area, a second helper called requireAdmin() calls requireAuth() and returns a 403 error if the user doesn't have the admin role.

Payments With Polar

I use Polar because it acts as Merchant of Record. Polar is the seller in the legal sense, so it handles sales tax and VAT for customers worldwide. As a solo founder, I don't want to file taxes in other countries.

Polar provides a better-auth plugin, so payments are part of the same setup:

server/utils/polar.ts
import { checkout, polar, portal } from '@polar-sh/better-auth'
import { createPolarCore } from '@polar-sh/sdk/2026-10'

export function setupPolar (accessToken: string, server: 'production' | 'sandbox') {
  return polar({
    client: createPolarCore({ accessToken, environment: server || undefined }),
    createCustomerOnSignUp: true,
    use: [
      checkout({
        authenticatedUsersOnly: true,
        successUrl: '/dashboard',
      }),
      portal(),
    ],
  })
}

With createCustomerOnSignUp, every new user gets a Polar customer at sign-up. That way, I never have to match a payment to a user by email later. checkout() only lets signed-in users buy, and portal() gives them Polar's customer portal to manage their subscription and invoices.

Set NUXT_PRIVATE_POLAR_SERVER to sandbox while you test, so you can buy with test cards in Polar's sandbox.

If you store access in your own database, you also need a webhook handler for Polar's events. Polar can send the same event more than once, so processing an event twice must have the same result as processing it once.

The Less Exciting Parts

These parts never show up in a demo video, but you need them before your first customer:

  • Database migrations you can run on a fresh database without surprises
  • Admin tools for user management, bans and impersonation
  • Security headers (I use Nuxt Security)
  • Transactional emails for verification and password reset
  • Error monitoring

My Build Order

When I start a new product, I go in this order:

  1. Auth and protected routes
  2. Database models for users and plans
  3. Checkout and access checks
  4. The core product loop
  5. Admin and monitoring
  6. Marketing pages and SEO content

If steps 1 to 3 are still open after a week, the foundation is slowing you down.

Conclusion

I'm very happy with this stack. better-auth and Polar work together through one plugin system, and both run in my own Nuxt server. I can deploy the whole app to any host that runs Node.js and PostgreSQL.

Of course, there are downsides. You are responsible for the session code, the payment flow and the database, and you have to update them when better-auth or Polar release breaking changes.

The code above is everything you need to start. Try it yourself.

All of this is already set up in Nuxt Starter Kit, together with the admin area, emails and security headers. Take a look at the docs or the live demo.

Skip the setup. Ship the product.

Nuxt Starter Kit gives you auth, payments, admin, and security on a Nuxt 4 foundation — so you can build features instead of plumbing.
View live demo
  • One-time payment
  • Lifetime updates
  • You own the code