Pular para o conteúdo principal

Next.js Authentication with Better Auth and PostgreSQL

Cadastro, login e logout com e-mail e senha para Next.js 16 com Better Auth, PostgreSQL no Docker, uma verificação das configurações na inicialização e testes.

  • Next.js
  • React
  • Better Auth
  • PostgreSQL
  • pg (node-postgres)

Capturas de tela

Captura 1 de 10: Capa do Next.js Authentication with Better Auth and PostgreSQL: a promessa, as tecnologias, um log real do npm run dev com um cadastro bem-sucedido e a página inicial com sessão iniciada no celular.

Capa do Next.js Authentication with Better Auth and PostgreSQL: a promessa, as tecnologias, um log real do npm run dev com um cadastro bem-sucedido e a página inicial com sessão iniciada no celular.

Pagamento único

  • ₹ 199+ GST, ₹ 234,82 no total
  • US$ 3
  • Baixe na sua biblioteca assim que o pagamento for confirmado.
  • Todas as versões futuras deste projeto estão incluídas, sem custo adicional.
Versão mais recente
1.0.0 · 19 de nov. de 2026

Visão geral

O código-fonte completo de um app Next.js 16 com Better Auth 1.7 para contas com e-mail e senha: páginas de cadastro e login com mensagens de erro claras, logout e um cabeçalho que mostra quem está conectado. As contas ficam no PostgreSQL 18 no Docker. O app verifica as configurações ao iniciar, e cinco testes cobrem essa verificação. Testado no macOS com o Docker Desktop.

O login parece coisa de dois formulários pequenos, mas também envolve senhas armazenadas como hash, um cookie de sessão seguro, mensagens de erro claras e configurações verificadas antes que algo quebre. O Next.js Authentication with Better Auth and PostgreSQL faz tudo isso com o Better Auth, a biblioteca de autenticação de código aberto para TypeScript, em um app pequeno que você pode rodar no seu computador e usar como base. Ele foi testado em execuções reais no macOS com o Docker Desktop.

O que ele faz

  • Cadastro com endereço de e-mail e senha. A página de cadastro cria a conta e faz o login da pessoa na hora.
  • Login e logout. A página de login conecta a pessoa de novo, e o botão Sign out encerra a sessão naquele navegador.
  • Mostra quem está conectado. O cabeçalho de todas as páginas mostra o nome da pessoa conectada com um botão Sign out, ou os links Sign in e Sign up, e muda sem recarregar a página.
  • Mensagens claras nos formulários. User already exists. Use another email. e Invalid email or password aparecem direto no formulário.

Padrões seguros do Better Auth

  • Nenhuma senha em texto puro. O Better Auth armazena no PostgreSQL apenas um hash scrypt de cada senha.
  • Sessões em um cookie HttpOnly. Os scripts da página não conseguem lê-lo, e uma sessão dura 7 dias por padrão.
  • Tamanho da senha verificado no servidor. De 8 a 128 caracteres, com o mesmo mínimo no formulário.

Feito para que os erros apareçam cedo

  • Verificação das configurações na inicialização. Se faltar BETTER_AUTH_SECRET, BETTER_AUTH_URL ou DATABASE_URL, ou se algum valor for inválido, o app para com uma lista clara do que corrigir.
  • Cinco testes para essa verificação, que rodam no executor de testes integrado ao Node.js, então não há framework de testes para instalar.
  • Verificações limpas. A checagem de tipos do TypeScript e o linter Biome passam sem erros, e o npm run build é concluído com sucesso.

Código para você construir em cima

  • Next.js 16 com o App Router, TypeScript 7, Tailwind CSS 4 e Biome.
  • Better Auth 1.7 com PostgreSQL por meio de um pool de conexões do pg: um lib/auth.ts curto, o manipulador de rota e o cliente React.
  • PostgreSQL 18 no Docker Compose, acessível apenas do seu próprio computador, na porta 5435.
  • Todas as configurações em um arquivo. Copie o .env.example para .env; o README explica cada valor.
  • Instalações reproduzíveis. Um package-lock.json com as versões exatas dos pacotes e um .nvmrc para o Node.js 26.

O que não está incluído

  • Sem e-mails. Não há verificação de e-mail nem redefinição de senha.
  • Sem login social, autenticação de dois fatores ou chaves de acesso.
  • Sem páginas protegidas. Todas as páginas são públicas; o cabeçalho mostra a sessão.
  • Sem hospedagem. O app roda no seu computador. Implantá-lo fica a seu critério.

Rode em seis etapas

  1. Instale o Node.js 26 LTS e inicie o Docker Desktop.
  2. Descompacte o download e abra um terminal na pasta dele.
  3. Rode npm install.
  4. Copie o .env.example para .env. Rode npx auth@latest secret e cole no .env a linha que ele exibir.
  5. Rode docker compose up -d, depois npx auth@latest migrate, e responda y.
  6. Rode npm run dev, abra http://localhost:3000 e clique em Sign up.

Cada etapa, com capturas de tela: How to Set Up and Run Next.js Authentication with Better Auth and PostgreSQL (abre em uma nova aba) (em inglês).

Aprenda as ideias por trás do código no tutorial gratuito Better Auth Tutorial for Beginners (abre em uma nova aba) (em inglês).

Better Auth, Next.js, PostgreSQL, Docker e os demais nomes mencionados são marcas comerciais de seus respectivos proprietários. Este projeto não é afiliado à Better Auth, Inc. nem à Vercel, nem endossado por elas.

Série de tutoriais gratuita

Better Auth Tutorial for Beginners

Prefere aprender construindo? Este guia gratuito e passo a passo no nosso blog mostra como o projeto é feito.

Ler a série (abre em uma nova aba)

O que você leva

Tudo o que está no arquivo, em um relance.

  • A versão 1.0.0 do código-fonte completo do app Next.js
  • Páginas de cadastro e login com mensagens de erro claras
  • Um cabeçalho que mostra quem está conectado, com um botão Sign out
  • O Better Auth 1.7 configurado com PostgreSQL, com seu manipulador de rota e seu cliente React
  • Um arquivo do Docker Compose que roda o PostgreSQL 18 no seu computador
  • Uma verificação das configurações que para o app com uma mensagem clara quando uma configuração está ausente ou é inválida
  • Cinco testes para a verificação das configurações
  • Um arquivo de configurações de exemplo, um arquivo de bloqueio de pacotes e um arquivo .nvmrc
  • Um README com os requisitos, a instalação, todas as configurações, os scripts e a solução de problemas

Feito com

As versões e os ambientes exatos com que foi criado e testado.

  • Next.js16.4.6
  • React19.3.1
  • Better Auth1.7.26
  • PostgreSQL18.7
  • pg (node-postgres)8.23.1
  • TypeScript7.0.2
  • Tailwind CSS4.3.5
  • Biome2.6.8
  • Node.js26.13.1
  • Docker Desktop4.99.0

O que há no arquivo

A árvore de pastas que você recebe ao descompactar.

nextjs-authentication-better-auth-postgresql/

  • .env.example
  • .gitattributes
  • .gitignore
  • .nvmrc
  • AGENTS.md
  • README.md
  • app/
    • api/
      • auth/
        • [...all]/
          • route.ts
    • favicon.ico
    • globals.css
    • layout.tsx
    • page.tsx
    • sign-in/
      • page.tsx
    • sign-up/
      • page.tsx
  • biome.json
  • components/
    • user-menu.tsx
  • compose.yaml
  • instrumentation.ts
  • lib/
    • auth-client.ts
    • auth.ts
    • env.ts
  • next.config.ts
  • package-lock.json
  • package.json
  • tests/
    • env.test.ts
  • tsconfig.json

O que ele precisa de você

As contas e os serviços que ele espera encontrar, para nada surpreender.

  • Node.js 26 LTS e npm
  • Docker com Docker Compose: Docker Desktop no macOS ou no Windows, ou Docker Engine no Linux. O Docker Desktop é gratuito para uso pessoal e pequenas empresas; organizações maiores precisam de uma assinatura paga
  • As portas 3000 (o app) e 5435 (o banco de dados) livres no seu computador
  • Nenhuma outra conta, chave de API ou serviço pago: tudo roda no seu computador

Versões

Todas as versões até agora, da mais recente para a mais antiga.

  1. 1.0.0Mais recente

    Primeira versão do código-fonte completo.

    • Cadastro, login e logout com e-mail e senha usando o Better Auth 1.7.26 no Next.js 16.4.6.
    • PostgreSQL 18 no Docker Compose, com as tabelas do Better Auth criadas por um único comando.
    • Uma verificação das configurações na inicialização, com cinco testes.

Source Code Licence

O que você pode fazer com ele

What you may and may not do with the source code you buy.

Ler a licença completa
  1. What this licence covers

This licence governs every file included in a product you buy from Dewiride Store: source code, configuration, database scripts, sample data, documentation and any other file in the download. It takes effect when your payment is confirmed and applies to every release of that product that reaches your library. Files that reach your library through an annual updates membership are governed in exactly the same way.

It forms part of the Terms of Sale and Use. Where a product page states different or additional licence terms for that product, those terms prevail for that product. The membership page may likewise state different or additional licence terms for the files a membership carries, and those terms then prevail for those files.

  1. The licence we grant you

We grant you a perpetual, worldwide, non-exclusive, non-transferable licence to use, reproduce, adapt, translate and modify the files, and to include the result in your own work, on the conditions set out below.

Perpetual means it does not expire. Worldwide means it is not limited to any country. Non-exclusive means we license the same product to other customers. Non-transferable means you cannot pass it on to someone else.

The licence is granted to you — either you personally, or the organisation you identified when buying. Everyone working within that organisation may use the files for that organisation’s projects. Nobody outside it may.

  1. What you may do
  • Use and change the files in your own projects, commercial or otherwise, with no limit on the number of projects.
  • Build a product or a service on them and charge your own customers for it.
  • Deploy the result for a client, as part of work you are doing for that client.
  • Distribute the result in compiled, deployed or otherwise non-source form.
  • Keep as many back-up copies as you reasonably need.
  • Study, observe and test how the code works, and obtain the information you need to make it work with your own software.

The last two are yours by law under sections 52(1)(aa) to (ac) of the Indian Copyright Act, 1957, and nothing in this licence is intended to take them away.

  1. What you may not do
  • Resell, sublicense, redistribute or publish the files themselves, in whole or in substantial part, in source form.
  • Include them in a template, starter kit, course, tutorial repository or component library that you sell or give away, where the code is the thing being supplied.
  • Share your account, your download links or your invoices with anyone outside your organisation.
  • Publish the files in a public repository, or in any other place where they can be obtained without buying them.
  • Remove or obscure the copyright and attribution notices in the source files.
  • Use the files to build something whose main purpose is to compete with Dewiride Store as a supplier of the same code.

The distinction that matters is simple: you may sell what you build with the code; you may not sell the code.

  1. Third-party components

Our products depend on open-source libraries, frameworks and services that we did not write. Those remain under their own licences, which we do not and cannot change. Where a product includes or requires such a component, its licence is named in the product’s documentation, and complying with it is your responsibility.

  1. Releases

Every release of a product you own is covered by this same licence and appears in your library at no extra cost. A release you have already downloaded remains licensed to you even if we later stop publishing the product. A release that reached your library through an annual updates membership is licensed to you on these same terms, and stays licensed after the period that carried it has ended.

  1. Ownership

We keep ownership of the files and of the copyright in them. You own whatever you create with them: your changes, your additions and the product you build are yours.

  1. If this licence ends

This licence ends if you materially breach it and do not put the breach right within thirty days of us asking you to in writing. It also ends if your payment is reversed or refunded, because the purchase it depends on no longer stands. Where a membership period is refunded or reversed, the licence ends for the releases that period carried and for nothing else: anything you bought separately, or that another period carried, is unaffected.

If it ends, you must stop using the files and delete the copies you hold. Work you had already delivered to a client before that point may continue in use, so that ending this licence never breaks something your own customer relies on.

  1. No warranty beyond the description

The warranties and limits in section 19 and section 20 of the Terms of Sale and Use apply to this licence as well.

  1. Governing law

This licence is governed by the law of India, and section 24 of the Terms of Sale and Use applies to any dispute about it. If a translation and the English version differ in meaning, the English version governs.