# How to add sign-in to a Next.js app

> Add sign-in to a Next.js app with one command using thelastapi to manage user sessions, email auth, and Google or GitHub logins.

**You can add sign-in to a Next.js app by enabling the `auth` resource and reading the current session directly from your server components.** thelastapi gives your project its own complete authentication service, managing user records, secure session cookies, email verification, and social logins without requiring third-party plugins. Your users stay stored inside your project's database, with separate environments automatically set up for local development and live production.

This guide walks through configuring authentication in Next.js, handling development versus production environments, enabling social sign-in, and securing your routes.

## What does the sign-in service provide?

When you add sign-in to a project, thelastapi provisions an authentication service and links it directly to a serverless Postgres database. You do not need to configure external user directories or run migrations for session tables.

The [Sign-in](https://thelastapi.dev/docs/sign-in) resource gives you:

- **Session and cookie handling**: Session cookies are signed cryptographically using your environment secret, preventing client-side tampering.
- **Multiple authentication flows**: Support for [email and password sign-in with verification codes](https://thelastapi.dev/blog/email-password-sign-in-verification), passwordless [magic link sign-in without building it yourself](https://thelastapi.dev/blog/magic-link-sign-in), and social logins.
- **Pre-configured social providers**: Turn on [Google sign-in without your own OAuth app](https://thelastapi.dev/blog/add-google-sign-in) using shared platform keys, or connect GitHub using your own application credentials.
- **Isolated environments**: Development runs against isolated tables and trusts `http://localhost:3000`, while production manages real customer data and enforces strict domain verification.

## How to start with a Next.js template

The quickest way to start a new project with authentication pre-configured is to scaffold the SaaS starter app. Run the following command in your terminal:

```bash
vibiz init "Acme App" --template nextjs-saas
cd acme-app
vibiz dev
```

The `vibiz init --template nextjs-saas` command bootstraps a Next.js project with authentication routes already wired in. Running `vibiz dev` provisions an isolated development database branch with your schema, spins up the local authentication service, and writes your local secrets to `.env.development.local`.

Inside the template, authentication endpoints are handled under `/api/auth/*`. To read the authenticated user in your server components or server actions, use the provided helper:

```ts
// app/dashboard/page.tsx
import { currentUser } from '@/lib/auth/server';

export default async function DashboardPage() {
  const user = await currentUser();

  if (!user) {
    return <p>Please sign in to access your dashboard.</p>;
  }

  return (
    <div>
      <h1>Welcome back, {user.email}</h1>
      <p>User ID: {user.id}</p>
    </div>
  );
}
```

If you prefer to deploy everything immediately without manual configuration, follow our guide to [deploy a Next.js app with a database and sign-in in one command](https://thelastapi.dev/blog/deploy-nextjs-app-database-sign-in).

## How to add sign-in to an existing Next.js project

If you have an existing Next.js codebase, you can add authentication without starting over. First, add the authentication resource to your project directory:

```bash
vibiz add auth
```

Adding `auth` automatically adds `database` if your project does not already have one, because user records are stored directly inside your project database.

Next, install the app SDK:

```bash
npm install --save-exact @vibiz/app@0.3.15
```

When running locally, initialize your development environment to pull your local authentication variables:

```bash
vibiz dev
```

This writes the required variables to `.env.development.local`. The following variables will be present:

| Variable | Description |
| --- | --- |
| `VIBIZ_AUTH_BASE_URL` | The sign-in service URL for the current environment |
| `VIBIZ_AUTH_COOKIE_SECRET` | Secret key used to sign and verify session cookies |
| `VIBIZ_AUTH_JWKS_URL` | Endpoint for token verification via JSON Web Key Sets |
| `VIBIZ_AUTH_PROJECT_ID` | The unique identifier for your project |
| `DATABASE_URL` | The direct Postgres connection string |

In your application entry point or server routes, you can load variables using the SDK:

```ts
import { vibiz } from '@vibiz/app';

await vibiz.loadEnv();
```

If your Next.js app is hosted outside thelastapi hosting, you only need to supply `VIBIZ_APP_KEY` in your host's environment settings. Calling `await vibiz.loadEnv()` at boot pulls the remaining authentication and database variables dynamically. Learn more about running standalone components in [Use one service](https://thelastapi.dev/docs/use-one).

## How to configure social sign-in and email methods

You can enable and customize authentication methods using the CLI or direct API requests. By default, changes made with the `--dev` flag apply only to your local development environment.

### Adding Google and GitHub

Google sign-in supports shared keys, allowing you to accept Google accounts immediately without setting up a Google Cloud project or OAuth consent screen:

```bash
vibiz auth providers add google --dev
```

GitHub requires your own OAuth app credentials. You can pass the client ID directly and provide the secret via environment variable or CLI prompt:

```bash
vibiz auth providers add github --own --client-id Iv1.abc --dev
```

To view your current development settings and callback URLs:

```bash
vibiz auth --dev
```

### Configuring email verification and magic links

You can manage allowed email domains, magic link expirations, and password verification behavior directly:

```bash
# Restrict sign-ups to specific corporate domains
vibiz auth domains acme.com,partner.com --dev

# Re-open sign-ups to all email addresses
vibiz auth domains none --dev
```

You can also update settings via the REST API:

```bash
curl -X PATCH "https://thelastapi.dev/v1/projects/prj_123/auth/settings?env=development" \
  -H "Authorization: Bearer $VIBIZ_API_KEY" \
  -H 'content-type: application/json' \
  -d '{
    "magic_link": {
      "enabled": true,
      "expires_in_minutes": 30
    },
    "allowed_email_domains": ["acme.com"]
  }'
```

The table below lists the available settings you can configure:

| Setting | Field | Default / Range |
| --- | --- | --- |
| App name in emails | `app_name` | 1–256 characters |
| Email + password | `email_password.enabled` | `true` or `false` |
| Require verification | `email_password.require_email_verification` | `true` or `false` |
| Verification method | `email_password.email_verification_method` | `otp` (code) or `link` (requires SMTP) |
| Closed sign-ups | `email_password.disable_sign_up` | `true` or `false` |
| Auto sign-in | `email_password.auto_sign_in_after_verification` | `true` or `false` |
| Magic links | `magic_link.enabled` | `true` or `false` |
| Magic link expiry | `magic_link.expires_in_minutes` | 5–1440 minutes |
| Allowed domains | `allowed_email_domains` | Array of up to 50 domains |
| Email sender | `email_sender` | `{ "type": "shared" }` or custom SMTP |

Note that link-style email verification requires your own custom SMTP server configuration. The shared sender sends one-time numeric verification codes (`otp`).

## How environments and domains work in production

Authentication behaves differently depending on whether your app is running locally or in production.

In development, the authentication service automatically trusts `http://localhost:3000`. In production, requests coming from untrusted domains are rejected to protect your session cookies from cross-site attacks.

### Using thelastapi hosting

If you deploy your app directly on thelastapi hosting, your production domain (such as `https://<slug>.vibiz.app`) is trusted automatically. When you buy a custom domain through the platform, DNS and SSL certificates configure automatically, and sign-in trusts the address immediately. See [Domains](https://thelastapi.dev/docs/domains) for details on purchasing and assigning custom names.

### Running on another host

If you run your Next.js application on another hosting provider, you must register your production web address so the sign-in service accepts incoming authentication callbacks:

```bash
vibiz domains add app.example.com --elsewhere
```

If you add the domain using a full-access owner key, it is trusted immediately. If an agent or CI key adds the domain using a Limited key, sign-in trusts the domain once you add the verification TXT record (`_vibiz.app.example.com`) and run:

```bash
vibiz domains verify app.example.com
```

Alternatively, the project owner can confirm the domain inside the web console. For more on managing permissions between owner keys and automation agents, see [Keys and environments](https://thelastapi.dev/docs/keys).

## Next step

Get your local authentication running in seconds by executing `vibiz init "My NextJS App" --template nextjs-saas` in your terminal, or read the complete [Sign-in reference](https://thelastapi.dev/docs/sign-in) to see full schema definitions and provider configurations.

## Frequently asked questions

### Do I need to create my own OAuth app to offer Google sign-in?

No. thelastapi provides shared keys for Google sign-in, allowing you to enable Google login immediately with `vibiz auth providers add google --dev` without creating credentials in the Google Cloud console.

### How does user authentication differ between local development and production?

Local development uses an isolated database branch with zero production records, allows localhost origins (`http://localhost:3000`), and runs its own authentication instance. Production uses your live database, enforces verified domain checks, and requires explicit owner approval for security settings.

### Can I restrict sign-ups to employees of a specific company?

Yes. You can set `allowed_email_domains` using `vibiz auth domains acme.com --dev` or via the API settings endpoint, which restricts account creation to up to 50 allowed email domains.

### What happens if I host my Next.js app on a third-party server?

You can host anywhere; simply add your domain using `vibiz domains add app.example.com --elsewhere` so the authentication service trusts the origin, and provide `VIBIZ_APP_KEY` to your host to load all required variables automatically.

---

Published 2026-11-15 · https://thelastapi.dev/blog/add-sign-in-nextjs-app
