---
title: "How to add auth to your Lovable app"
description: "A step-by-step tutorial to adding authentication to your Lovable app with WorkOS AuthKit."
url: https://workos.com/blog/how-to-add-auth-to-your-lovable-app
published: "Mar 05, 2026"
---

# How to add auth to your Lovable app

Lovable makes it incredibly fast to go from idea to working app. In minutes, you can have a full-stack Next.js application with a frontend, backend, and database; all generated from natural language prompts. But there's one thing most Lovable apps need before you can share them with real users: proper authentication.

By default, Lovable gives you basic auth scaffolding. That works fine for demos, but when you want to ship (whether to individual users or to enterprise customers) you need something more robust. [WorkOS AuthKit](https://www.authkit.com/) gives you a production-ready auth layer with support for email/password, social login, passwordless, MFA, passkeys, and enterprise SSO, all in a few lines of code.

In this tutorial, we'll walk through adding WorkOS authentication to a Lovable-generated Next.js app step by step.

## **Prerequisites**

- A [Lovable](https://lovable.dev/) app (exported or connected to a GitHub repo).
- A [WorkOS account](https://dashboard.workos.com/sign-up) (free for up to 1 million active users, no credit card required).
- Node.js installed locally.

> **Want to skip the manual setup?** The [CLI Installer](https://workos.com/docs/authkit/cli-installer) detects your framework, installs the SDK, configures your dashboard, and writes the integration code, all with a single command.

[Embedded media](https://www.youtube.com/embed/kU88lUqdduQ)

## **Step 1: Install the Next.js SDK**

Open your terminal in the root of your Lovable project and install the AuthKit Next.js [SDK](https://workos.com/docs/sdks):

```js
npm install @workos-inc/authkit-nextjs
```

## **Step 2: Configure your WorkOS dashboard**

Before writing any code, you need to configure two things in the [WorkOS dashboard](https://dashboard.workos.com/environment/redirects).

1. **Set a redirect URI** → this is the callback endpoint WorkOS will redirect to after a user authenticates. Go to the [**Redirects**](https://dashboard.workos.com/environment/redirects) section of the Dashboard and add: `http://localhost:3000/callback`
2. **Set a sign-in endpoint** → this tells AuthKit where to send users if they land on the hosted sign-in page directly (e.g. from a bookmarked link or a password reset email). In the same [**Redirects**](https://dashboard.workos.com/environment/redirects) section, set your sign-in endpoint to: `http://localhost:3000/login`

![Screenshot of WorkOS dashboard](https://cdn.prod.website-files.com/621f84dc15b5ed16dc85a18a/69a9b35af5e781241b9178df_2.webp)

You'll update both of these to your production domain before deploying.

## **Step 3: Configure your environment variables**

Grab your API key and client ID from the [WorkOS dashboard](https://dashboard.workos.com/).

![Screenshot of WorkOS dashboard](https://cdn.prod.website-files.com/621f84dc15b5ed16dc85a18a/69a9b36c71a5d7146c7d8c29_5.webp)

Then create a `.env.local` file in the root of your project:

```js
WORKOS_API_KEY='sk_example_123456789'
WORKOS_CLIENT_ID='client_123456789'
WORKOS_COOKIE_PASSWORD="your-secure-32-character-password-here"
NEXT_PUBLIC_WORKOS_REDIRECT_URI="http://localhost:3000/callback"
```

`WORKOS_COOKIE_PASSWORD` is used to encrypt cookies and must be at least 32 characters long. You can generate a secure password by using the [1Password generator](https://1password.com/password-generator/) or the `openssl` library via the command line:

```js
openssl rand -base64 32
```

Note: `NEXT_PUBLIC_WORKOS_REDIRECT_URI` uses the `NEXT_PUBLIC_` prefix so it's accessible in edge functions and proxy configurations (useful for Vercel preview deployments).

## Step 4: Wrap your app layout with AuthKitProvider

`AuthKitProvider` adds protections for auth edge cases and is required to wrap your app. Open your root layout file (`app/layout.tsx`) and add it:

```js
// app/layout.tsx
import { AuthKitProvider } from '@workos-inc/authkit-nextjs/components';

export default function RootLayout({ children }: { children: React.ReactNode }) {
  return (
    <html lang="en">
      <body>
        <AuthKitProvider>
          {children}
        </AuthKitProvider>
      </body>
    </html>
  );
}
```

Your existing Lovable-generated components stay exactly as they are; the provider just wraps around them.

## Step 5: Add the proxy

The proxy controls which routes require authentication. In Next.js 16+, this lives in `proxy.ts` (previously `middleware.ts`) at the root of your project.

For most Lovable apps, middleware auth mode is the right default: all routes are protected unless explicitly listed as public.

```js
// proxy.ts
import { authkitMiddleware } from '@workos-inc/authkit-nextjs';

export default authkitMiddleware({
  middlewareAuth: {
    enabled: true,
    unauthenticatedPaths: ['/', '/pricing', '/about'], // pages anyone can access
  },
});

// Match against the pages in your app
export const config = { matcher: ['/', '/account/:page*'] };
```

Any route not listed in `unauthenticatedPaths` will require a signed-in user. Unauthenticated visitors are automatically redirected to the WorkOS-hosted AuthKit login page.

> If you're on Next.js 15 or earlier, name this file `middleware.ts` instead.

## Step 6: Create the login and callback routes

You need two route handlers: one to kick off the sign-in flow, and one to handle the redirect back from WorkOS after a successful login.

```js
// app/login/route.ts
import { getSignInUrl } from '@workos-inc/authkit-nextjs';
import { redirect } from 'next/navigation';

export const GET = async () => {
  const signInUrl = await getSignInUrl();
  return redirect(signInUrl);
};
```

```js
// app/callback/route.ts
import { handleAuth } from '@workos-inc/authkit-nextjs';

// Redirects to `/` after successful sign in by default
// Customize with: handleAuth({ returnPathname: '/dashboard' })
export const GET = handleAuth();
```

## Step 7: Update your landing page

Your home page should handle both authenticated and unauthenticated visitors:

```js
// app/page.tsx
import Link from 'next/link';
import { getSignUpUrl, withAuth, signOut } from '@workos-inc/authkit-nextjs';

export default async function HomePage() {
  // Returns the user from the session, or null if not signed in
  const { user } = await withAuth();
  const signUpUrl = await getSignUpUrl();

  if (!user) {
    return (
      <main>
        <h1>Welcome to My App</h1>
        <p>Please sign in to continue.</p>
        <Link href="/login">Sign in</Link>
        {' | '}
        <Link href={signUpUrl}>Sign up</Link>
      </main>
    );
  }

  return (
    <main>
      <h1>Welcome back{user.firstName && `, ${user.firstName}`}</h1>
      <p>Email: {user.email}</p>
      <form
        action={async () => {
          'use server';
          await signOut();
        }}
      >
        <button type="submit">Sign out</button>
      </form>
    </main>
  );
}
```

> Make sure you've configured a **Sign-out redirect** in the WorkOS dashboard (same [**Redirects**](https://dashboard.workos.com/environment/redirects) section). Without it, users will see an error after signing out.

## Step 8: Protect your dashboard

For routes where a signed-in user is mandatory, use `withAuth` with `ensureSignedIn: true`. This automatically redirects unauthenticated users to the login flow:

```js
// app/dashboard/page.tsx
import { withAuth } from '@workos-inc/authkit-nextjs';

export default async function Dashboard() {
  // Automatically redirects to login if not authenticated
  const { user } = await withAuth({ ensureSignedIn: true });

  return (
    <div>
      <h1>Dashboard</h1>
      <p>Welcome back{user.firstName && `, ${user.firstName}`}</p>

      {/* Your Lovable-generated components go here, unchanged */}
    </div>
  );
}
```

## Testing it locally

Start your dev server:

```js
npm run dev
```

Visit `http://localhost:3000/dashboard` — you should be redirected to the WorkOS-hosted AuthKit login page. Sign up for a new account and you'll land back in your app as an authenticated user.To confirm everything is wired up correctly, open the [WorkOS Dashboard](https://dashboard.workos.com/) and check the **Users** section — you should see your newly created account listed there.

## What you get for free

Once AuthKit is wired up, you're not just getting a login form. WorkOS handles:

- [**Email + password auth**](https://workos.com/docs/authkit/email-password): Automatic password strength and leak detection.
- [**Social login**](https://workos.com/docs/authkit/social-login) (Google, GitHub, Microsoft, etc.) with a single toggle in the dashboard.
- [**Magic auth**](https://workos.com/docs/authkit/magic-auth) for passwordless sign-in.
- [**Multi-Factor Auth (MFA)**](https://workos.com/docs/authkit/mfa): Additional authentication with TOTP and SMS.
- [**Biometric / Passkey Auth**](https://workos.com/docs/authkit/passkeys): Passwordless authentication with passkeys.
- [**CLI Authentication**](https://workos.com/docs/authkit/cli-auth)**:** Quickly add auth to your command-line tools.
- [**Email verification**](https://workos.com/docs/authkit/email-verification): Verify user email addresses with magic codes.
- [**Organization auth policies**](https://workos.com/docs/authkit/organization-policies)**:** Restrict domains, MFA, and SSO per organization.
- [**Just-in-time (JIT) user provisioning**](https://workos.com/docs/authkit/jit-provisioning): Automatic provisioning based on email or SSO.
- [**Role-Based Access Control (RBAC)**](https://workos.com/docs/rbac) and [**Fine-Grained Authorization (FGA)**](https://workos.com/docs/fga):  Powerful and flexible permissions for your users.
- [**Admin Portal**](https://workos.com/docs/admin-portal)**:** A self-serve UI your enterprise customers can use to configure SSO themselves.
- And more.

## Deploying to production

Before deploying, update your environment variables and WorkOS Dashboard to use your production domain:

```js
NEXT_PUBLIC_WORKOS_REDIRECT_URI="https://yourdomain.com/callback"
```

In the WorkOS Dashboard under **Redirects**, add `https://yourdomain.com/callback` as an allowed redirect URI, update your sign-in endpoint to `https://yourdomain.com/login`, and set your sign-out redirect to wherever you want users to land after logging out.

## Next steps

With auth in place, your Lovable app is ready for real users. If you're targeting enterprise customers, WorkOS also gives you:

- [**Enterprise SSO**](https://workos.com/sso): When an enterprise customer wants to sign in with Okta, Azure AD, or Google Workspace, WorkOS handles the full SAML/OIDC flow automatically.
- [**Directory Sync**](https://workos.com/docs/directory-sync): Automatically provision and deprovision users from Okta, Azure AD, and more.
- [**Audit Logs**](https://workos.com/docs/audit-logs): A tamper-proof record of every action in your app.
- [**Radar**](https://workos.com/docs/authkit/radar)**:** Realtime protection against bots, fraud, and abuse.
- [**Feature Flags**](https://workos.com/docs/feature-flags)**:** Manage rollout of new features for specific users and organizations.
- And more.

You can add all of these incrementally as your needs grow; no need to rearchitect anything.

[Get started with WorkOS today.](https://dashboard.workos.com/sign-up)
