# Using @saastro/forms without Vite (Next.js)

URL: https://docs.forms.saastro.io/docs/recipes/nextjs-without-vite
> Pass the UI components explicitly instead of import.meta.glob — a contact form as a Next.js Client Component with an HTTP submit action.

# Using @saastro/forms without Vite (Next.js)

## What it combines

The zero-config examples in these docs discover components with `import.meta.glob`, which is a **Vite-only** feature. On Next.js (or webpack, Rspack, esbuild, …) you pass the components explicitly via the `components` prop instead. Everything else works the same.

This recipe combines:

- **Explicit component injection** — a plain `components` object ([Component System](/docs/components))
- **An HTTP submit action** — posting JSON to your own route handler ([Submit & Actions](/docs/submit))
- **The App Router client boundary** — the form is a Client Component

```tsx
// components/contact-form.tsx
'use client';

import { Form, FormBuilder } from '@saastro/forms';

// Explicit imports replace import.meta.glob
import { Button } from '@/components/ui/button';
import { Field, FieldDescription, FieldError, FieldLabel } from '@/components/ui/field';
import { FormControl, FormField } from '@/components/ui/form';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from '@/components/ui/select';
import { Textarea } from '@/components/ui/textarea';

export const components = {
  // Always required
  Button,
  Field,
  FieldLabel,
  FieldDescription,
  FieldError,
  // text / email / textarea fields
  Input,
  Textarea,
  Label,
  FormField,
  FormControl,
  // select field
  Select,
  SelectTrigger,
  SelectContent,
  SelectItem,
  SelectValue,
};

export function createConfig({ endpoint }: { endpoint: string }) {
  return FormBuilder.create('contact')
    .addField('name', (f) => f.type('text').label('Name').required().minLength(2))
    .addField('email', (f) => f.type('email').label('Email').required().email())
    .addField('topic', (f) =>
      f
        .type('select')
        .label('Topic')
        .required()
        .options([
          { value: 'sales', label: 'Sales' },
          { value: 'support', label: 'Support' },
        ]),
    )
    .addField('message', (f) => f.type('textarea').label('Message').required().rows(5))
    .addStep('main', ['name', 'email', 'topic', 'message'])
    .buttons({ submit: { type: 'submit', label: 'Send' } })
    .submitAction(
      'save',
      {
        type: 'http',
        name: 'Save contact',
        endpoint: { url: endpoint, method: 'POST' },
        body: { format: 'json' },
      },
      'onSubmit',
    )
    .successMessage("Thanks! We'll get back to you soon.")
    .errorMessage('Something went wrong — please try again.')
    .build();
}

const config = createConfig({ endpoint: '/api/contact' });

export function ContactForm() {
  return <Form config={config} components={components} />;
}
```

## The code

### 1. Install

```bash
npm install @saastro/forms react-hook-form zod date-fns react-day-picker
```

Then add the shadcn/ui primitives this recipe needs (run `npx shadcn@latest init` first if you haven't):

```bash
npx shadcn@latest add input textarea select button label field form
```

### 2. The form — a Client Component

The **Code** tab above is the whole file. `<Form />` is interactive React (hooks, context, react-hook-form), so in the App Router the file that renders it must be a **Client Component** — start it with `'use client'`. Build the config in the same module: a `FormConfig` can contain functions (handlers, dynamic messages, custom schemas), which cannot be passed as props across the server → client boundary.

### 3. Use it from a page

The page itself can stay a Server Component — it just renders the client component:

```tsx
// app/contact/page.tsx
import { ContactForm } from '@/components/contact-form';

export default function ContactPage() {
  return (
    <main className="mx-auto max-w-xl py-12">
      <h1 className="mb-8 text-2xl font-semibold">Contact us</h1>
      <ContactForm />
    </main>
  );
}
```

And a minimal route handler for the HTTP submit action:

```ts
// app/api/contact/route.ts
export async function POST(req: Request) {
  const data = await req.json();
  // store the submission, forward it to your CRM, send an email, ...
  console.log('contact submission', data);
  return Response.json({ ok: true });
}
```

## How it works

- **Explicit components** — the `components` object replaces `import.meta.glob`: each key is a slot the package renders (`Button`, `Field`, `Input`, `Select`, …) and each value is your component.
- **Which components do I need?** It depends on your field types. If one is missing, the form renders an inline warning naming it. You can also check programmatically:

  ```tsx
  import { getRequiredComponents, getInstallCommand } from '@saastro/forms';

  const required = getRequiredComponents(config); // ['Input', 'Button', 'Field', ...]
  const cmd = getInstallCommand(required); // 'npx shadcn@latest add ...'
  ```

  The full per-field-type table is in the [Installation guide](/docs/installation).

- **HTTP action** — the `http` submit action posts the values as JSON to `/api/contact`; a failed response fails the submission and shows `errorMessage`.

## Caveats

- **ESM only** — `@saastro/forms` ships as ESM with no CommonJS build. Next.js handles ESM packages natively; no `transpilePackages` entry is needed.
- **Tailwind CSS 4** — add `@source "node_modules/@saastro/forms/dist/**/*.js";` to your main CSS file so Tailwind picks up the classes used by the package. See [Styling](/docs/styling).
- **Pages Router** — works the same; there are no Server Components, so just render `<ContactForm />` from any page (the `'use client'` directive is simply ignored there).

## Variations

- **Many forms, one app** — instead of repeating the `components` object per form, define it once in a shared module (e.g. `lib/form-components.ts`) and import it wherever you render a `<Form>`. The available registry slots and provider-based alternatives are covered in [Component System](/docs/components).
- Replace the `http` action with a `webhook` action — see [Multi-step lead form with conditional routing and a webhook](/docs/recipes/multi-step-webhook).

## Related

- [Component System](/docs/components)
- [Installation](/docs/installation)
- [Submit & Actions](/docs/submit)
