/how-to-build-lovable

How to build Authentication system with Lovable?

Step-by-step guide to building a secure, scalable authentication system with Lovable. Learn best practices, code examples, and deployment tips.

Matt Graham, CEO of Rapid Developers

Book a call with an Expert

Starting a new venture? Need to upgrade your web app? RapidDev builds application with your growth in mind.

Book a free No-Code consultation

How to build Authentication system with Lovable?

You can build a production-capable authentication flow in Lovable by using a hosted auth provider (I recommend Supabase Auth), storing the Supabase URL and anonymous key in Lovable Cloud Secrets, and then using Chat Mode edits to add a Supabase client, React AuthContext, Signup/Login pages, and a ProtectedRoute component. Do everything inside Lovable (no terminal). If you need DB migrations or server-side functions that require a CLI, export to GitHub from Lovable and run those steps outside Lovable (I’ll call that out where required).

 

What we’re building / changing (plain English)

 

Client-side authentication with Supabase. We’ll add a Supabase client, a React AuthContext that keeps current user and session, Signup & Login pages, and a ProtectedRoute wrapper so pages/components can require auth. Secrets (SUPABASE_URL, SUPABASE_ANON\_KEY) will be stored in Lovable Cloud Secrets. No CLI needed.

 

Lovable-native approach

 

Workflow: Use Chat Mode in Lovable to create/modify files (I provide prompts you paste into Lovable). Use Lovable Cloud Secrets UI to add SUPABASE_URL and SUPABASE_ANON\_KEY. Use Preview to test flow locally in Lovable. Use Publish to deploy Lovable Cloud. If you must run CLI-only tasks (rare for this flow), export to GitHub and run them outside Lovable.

 

Meta-prompts to paste into Lovable (one by one)

 

Prompt 1 — Add dependency and Supabase client

 

Goal: Add supabase client wrapper and package.json dependency.

  • Files to create/modify: update package.json (add dependency "supabase-js": "^2.0.0"), create src/lib/supabaseClient.ts
  • Acceptance criteria: done when package.json contains supabase-js and src/lib/supabaseClient.ts exports a createClient instance that reads keys from process.env (so Lovable Secrets map to env vars at runtime).
  • Secrets/setup: In Lovable Cloud Secrets UI create SUPABASE_URL and SUPABASE_ANON\_KEY
// Update package.json dependencies: ensure "supabase-js": "^2.0.0" is listed
// Create file src/lib/supabaseClient.ts

import { createClient } from '@supabase/supabase-js'

// Read values from env so Lovable Secrets will be used
const supabaseUrl = process.env.SUPABASE_URL || ''
const supabaseAnonKey = process.env.SUPABASE_ANON_KEY || ''

export const supabase = createClient(supabaseUrl, supabaseAnonKey)

 

Prompt 2 — Add AuthContext and session management

 

Goal: Create a React context that exposes user, signIn, signUp, signOut and keeps session via onAuthStateChange.

  • Files to create/modify: create src/contexts/AuthContext.tsx and update src/App.tsx (or your top-level entry) to wrap the app with
  • Acceptance criteria: done when AuthContext provides currentUser and functions and automatically updates on login/logout.
// Create src/contexts/AuthContext.tsx

import React, { createContext, useContext, useEffect, useState } from 'react'
import { supabase } from '../lib/supabaseClient'

// Define types as needed
export const AuthContext = createContext(null)

export function AuthProvider({ children }) {
  const [user, setUser] = useState(null)

  useEffect(() => {
    // check initial session
    supabase.auth.getSession().then(({ data }) => {
      setUser(data.session?.user || null)
    })
    const { data: listener } = supabase.auth.onAuthStateChange((_event, session) => {
      setUser(session?.user || null)
    })
    return () => listener?.subscription?.unsubscribe?.()
  }, [])

  const signUp = (email, password) => supabase.auth.signUp({ email, password })
  const signIn = (email, password) => supabase.auth.signInWithPassword({ email, password })
  const signOut = () => supabase.auth.signOut()

  return <AuthContext.Provider value={{ user, signUp, signIn, signOut }}>{children}</AuthContext.Provider>
}

export const useAuth = () => useContext(AuthContext)
// Update src/App.tsx to wrap app with AuthProvider
import { AuthProvider } from './contexts/AuthContext'

function App() {
  return (
    <AuthProvider>
      {/* existing app UI */}
    </AuthProvider>
  )
}
export default App

 

Prompt 3 — Add Signup, Login and ProtectedRoute UI

 

Goal: Create UI pages for Signup and Login and a ProtectedRoute wrapper component.

  • Files to create/modify: create src/pages/Signup.tsx, src/pages/Login.tsx, src/components/ProtectedRoute.tsx
  • Acceptance criteria: done when a user can sign up, sign in, and ProtectedRoute only renders children when user exists (otherwise redirects to Login).
// src/pages/Signup.tsx
import React, { useState } from 'react'
import { useAuth } from '../contexts/AuthContext'

// simple signup form
export default function Signup() {
  const { signUp } = useAuth()
  const [email, setEmail] = useState('')
  const [password, setPassword] = useState('')
  const [msg, setMsg] = useState('')
  const submit = async (e) => {
    e.preventDefault()
    const { error } = await signUp(email, password)
    setMsg(error ? error.message : 'Check your email for confirmation (if enabled)')
  }
  return (
    // simple form UI
  )
}
// src/pages/Login.tsx
import React, { useState } from 'react'
import { useAuth } from '../contexts/AuthContext'
export default function Login() {
  const { signIn } = useAuth()
  // similar form and handle success to show protected content
}
// src/components/ProtectedRoute.tsx
import React from 'react'
import { useAuth } from '../contexts/AuthContext'

export default function ProtectedRoute({ children }) {
  const { user } = useAuth()
  if (!user) {
    // render a link to /login or a message
    return <div>Please log in to access this page.</div>
  }
  return <>{children}</>
}

 

How to verify in Lovable Preview

 

  • Open Preview, navigate to Signup page, create an account (use email/password), then Login. After login, open a page wrapped with ProtectedRoute and confirm it shows content. If you see the protected content, it's working.

 

How to Publish / re-publish

 

  • Use Lovable Publish button to deploy the app with the Secrets attached. Confirm that Lovable Cloud has the same SUPABASE_URL and SUPABASE_ANON\_KEY stored.
  • If you need external deployment with server-side functions: export/sync to GitHub from Lovable and run CI/deploy steps outside Lovable (terminal required).

 

Common pitfalls in Lovable (and how to avoid them)

 

  • Forgetting Secrets: App will fail silently or show auth errors — add SUPABASE_URL and SUPABASE_ANON\_KEY via Lovable Secrets UI.
  • Using a service-role key in the browser: never store SERVICE\_ROLE in client secrets. Use anon/public key for client SDK; keep service role only for server functions (then use GitHub export to run server-side code).
  • CORS / Redirect URL: Ensure your Supabase project has the Preview app origin (copy the Preview URL) added to allowed redirect/allowed origins in Supabase Auth settings.
  • Assuming terminal is available: Lovable has no terminal — any CLI steps must be done outside via GitHub export.

 

Validity bar

 

Accurate: This uses Lovable-native actions (Chat Mode edits, Preview, Publish, Secrets UI, GitHub export for external CLI). No invented Lovable features are used. If your app uses a framework with different file locations (Next.js, Remix), adapt file paths (e.g., pages/api or app/layout) — ask if you want that adapted and I’ll provide framework-specific prompts.

Want to explore opportunities to work with us?

Connect with our team to unlock the full potential of no-code solutions with a no-commitment consultation!

Book a Free Consultation

How to add progressive failed-login lockouts with email unlocks

This prompt helps an AI assistant understand your setup and guide to build the feature

AI AI Prompt

How to add server-side password hygiene with HIBP k-anonymity

This prompt helps an AI assistant understand your setup and guide to build the feature

AI AI Prompt

How to add session management & revocation to Lovable auth

This prompt helps an AI assistant understand your setup and guide to build the feature

AI AI Prompt

Want to explore opportunities to work with us?

Connect with our team to unlock the full potential of no-code solutions with a no-commitment consultation!

Book a Free Consultation
Matt Graham, CEO of Rapid Developers

Book a call with an Expert

Starting a new venture? Need to upgrade your web app? RapidDev builds application with your growth in mind.

Book a free No-Code consultation

Best Practices for Building a Authentication system with AI Code Generators

The short answer: use a managed auth provider when possible (Supabase/Clerk/Auth0), keep all secrets in Lovable’s Secrets UI, do session and token verification only on server-side Lovable functions, review and test every AI-generated change in Preview, and treat AI generators as a helper — not an authority. Don’t run or expect CLI steps inside Lovable; perform migrations or advanced tooling via GitHub sync/CI and external services.

 

Authentication architecture choices

 

Pick a managed auth unless you have a strong reason not to. Managed providers handle password storage, MFA, OAuth flows, refresh logic, and security updates. In Lovable projects I shipped, Supabase and Auth0 reduced surface area dramatically.

  • Managed provider benefits: fewer secrets to manage, built-in email/OAuth, client SDKs that work in-browser, and server-side verification endpoints you can call from Lovable functions.
  • When to roll your own: you need custom flows or on-prem constraints — then build JWT sessions, secure httpOnly cookies, refresh tokens, CSRF protection, and rate limits.

 

Secrets, environment, and Lovable constraints

 

Always store API keys and private keys in Lovable’s Secrets UI. Never embed service\_role keys or secret keys into generated code in the repo. Preview will run with those Secrets, Publish will too, but GitHub export will not include Secrets.

  • Client keys that are intended public (like Supabase anon key) can be in code, but keep service\_role keys, JWT signing keys, and OAuth client secrets only in Secrets UI.
  • No terminal in Lovable: database migrations, heavy CLI tasks, or secret rotations should be done via external CI/GitHub actions or the provider console.

 

Server-side verification and session management

 

Always validate tokens on server-side Lovable functions (these run in Lovable Cloud). Use httpOnly, Secure, SameSite cookies for sessions so client-side JS can't read tokens. Keep refresh tokens out of browser-accessible storage.

  • Example pattern: client does OAuth/passwordless with provider SDK, receives a short-lived access token, then POSTs it to your Lovable serverless endpoint which verifies it (using provider API or your JWT secret) and then sets a secure httpOnly cookie for app sessions.
// /api/session.js - serverless handler in Lovable project
import jwt from 'jsonwebtoken' // make sure package.json includes jsonwebtoken

// ! Use JWT_SECRET stored in Lovable Secrets UI (process.env.JWT_SECRET)
export default async function handler(req, res) {
  // POST { token } from client after provider login
  const { token } = req.body
  try {
    // Verify provider token if needed, or trust and mint your cookie token
    // // For a custom JWT issuer:
    const payload = jwt.verify(token, process.env.JWT_SECRET) // // verify provider/custom token
    // // Mint app cookie
    const appToken = jwt.sign({ sub: payload.sub }, process.env.JWT_SECRET, { expiresIn: '1h' })
    res.setHeader('Set-Cookie', `app_token=${appToken}; HttpOnly; Secure; SameSite=Strict; Path=/; Max-Age=3600`)
    res.status(200).json({ ok: true })
  } catch (err) {
    res.status(401).json({ error: 'Unauthorized' })
  }
}

 

AI code-generator workflow & safety

 

Treat AI output as a draft. Always review for security issues: leaking secrets, missing validation, insecure cookie attributes, missing CSRF, and dangerous redirects. Use Chat Mode edits and file diffs to iterate; don’t accept large bulk changes without manual review.

  • Reject any generated change that hardcodes Secrets. Replace with process.env.\* and configure via Secrets UI.
  • Use Preview to run the change in a safe environment with your Secrets injected to validate behavior before Publish.

 

Testing, migrations, and GitHub sync

 

Use Preview for runtime testing and export to GitHub when you need CI, migrations, or more control. Run DB migrations from CI or provider consoles — Lovable has no built-in terminal to run migrations.

  • Set up GitHub actions to run migrations after Publish or on merge to main; keep migration credentials in GitHub Secrets, not in the repo.

 

Quick checklist before Publish

  • Secrets in Secrets UI
  • Server-side token verification in Lovable functions
  • Secure cookie attributes and CSRF protection
  • AI-generated code audited in Preview
  • Migrations delegated to external CI or provider console

Client trust and success are our top priorities

When it comes to serving you, we sweat the little things. That’s why our work makes a big impact.

Rapid Dev was an exceptional project management organization and the best development collaborators I've had the pleasure of working with. They do complex work on extremely fast timelines and effectively manage the testing and pre-launch process to deliver the best possible product. I'm extremely impressed with their execution ability.

CPO, Praction - Arkady Sokolov

May 2, 2023

Working with Matt was comparable to having another co-founder on the team, but without the commitment or cost. He has a strategic mindset and willing to change the scope of the project in real time based on the needs of the client. A true strategic thought partner!

Co-Founder, Arc - Donald Muir

Dec 27, 2022

Rapid Dev are 10/10, excellent communicators - the best I've ever encountered in the tech dev space. They always go the extra mile, they genuinely care, they respond quickly, they're flexible, adaptable and their enthusiasm is amazing.

Co-CEO, Grantify - Mat Westergreen-Thorne

Oct 15, 2022

Rapid Dev is an excellent developer for no-code and low-code solutions.
We’ve had great success since launching the platform in November 2023. In a few months, we’ve gained over 1,000 new active users. We’ve also secured several dozen bookings on the platform and seen about 70% new user month-over-month growth since the launch.

Co-Founder, Church Real Estate Marketplace - Emmanuel Brown

May 1, 2024 

Matt’s dedication to executing our vision and his commitment to the project deadline were impressive. 
This was such a specific project, and Matt really delivered. We worked with a really fast turnaround, and he always delivered. The site was a perfect prop for us!

Production Manager, Media Production Company - Samantha Fekete

Sep 23, 2022