Next.js Authentication with Better Auth and PostgreSQL
Registro, inicio y cierre de sesión con correo electrónico y contraseña para Next.js 16 con Better Auth, PostgreSQL en Docker, una comprobación de ajustes al arrancar y pruebas.
- Next.js
- React
- Better Auth
- PostgreSQL
- pg (node-postgres)
Capturas de pantalla
Pago único
- 199 INR+ GST, 234,82 INR en total
- 3 US$
- Descárgalo desde tu biblioteca en cuanto se confirme tu pago.
- Incluye todas las versiones futuras de este proyecto, sin costo adicional.
- Última versión
- 1.0.0 · 19 nov 2026
- Licencia
- Source Code Licence
Descripción general
El código fuente completo de una app Next.js 16 con Better Auth 1.7 para cuentas de correo y contraseña: páginas de registro e inicio de sesión con mensajes de error claros, cierre de sesión y un encabezado que muestra quién está conectado. Las cuentas se guardan en PostgreSQL 18 en Docker. La app revisa sus ajustes al arrancar, algo que cubren cinco pruebas. Probado en macOS con Docker Desktop.
El inicio de sesión parece cosa de dos formularios pequeños, pero también supone contraseñas guardadas como hash, una cookie de sesión segura, mensajes de error claros y ajustes que se comprueban antes de que algo falle. Next.js Authentication with Better Auth and PostgreSQL hace todo eso con Better Auth, la biblioteca de autenticación de código abierto para TypeScript, en una pequeña app que puedes ejecutar en tu equipo y usar como base. Se probó en ejecuciones reales en macOS con Docker Desktop.
Qué hace
- Registro con una dirección de correo electrónico y una contraseña. La página de registro crea la cuenta e inicia la sesión de la persona al instante.
- Inicio y cierre de sesión. La página de inicio de sesión vuelve a iniciar la sesión de la persona, y el botón Sign out cierra la sesión en ese navegador.
- Muestra quién ha iniciado sesión. El encabezado de cada página muestra el nombre de la persona que ha iniciado sesión con un botón Sign out, o los enlaces Sign in y Sign up, y cambia sin recargar la página.
- Mensajes claros en los formularios.
User already exists. Use another email.eInvalid email or passwordaparecen directamente en el formulario.
Seguridad predeterminada de Better Auth
- Sin contraseñas en texto plano. Better Auth solo guarda en PostgreSQL un hash scrypt de cada contraseña.
- Sesiones en una cookie HttpOnly. Los scripts de la página no pueden leerla, y una sesión dura 7 días de forma predeterminada.
- Longitud de la contraseña comprobada en el servidor. De 8 a 128 caracteres, con el mismo mínimo en el formulario.
Hecha para que los errores aparezcan pronto
- Una comprobación de ajustes al arrancar. Si
BETTER_AUTH_SECRET,BETTER_AUTH_URLoDATABASE_URLfalta o no es válido, la app se detiene con una lista clara de lo que hay que corregir. - Cinco pruebas para esa comprobación, con el ejecutor de pruebas integrado en Node.js, así que no hay ningún framework de pruebas que instalar.
- Comprobaciones limpias. La comprobación de tipos de TypeScript y el linter Biome pasan sin errores, y
npm run buildse completa correctamente.
Código sobre el que construir
- Next.js 16 con el App Router, TypeScript 7, Tailwind CSS 4 y Biome.
- Better Auth 1.7 con PostgreSQL mediante un pool de conexiones de
pg: unlib/auth.tscorto, el controlador de ruta y el cliente de React. - PostgreSQL 18 en Docker Compose, accesible solo desde tu propio equipo, en el puerto 5435.
- Todos los ajustes en un solo archivo. Copia
.env.examplecomo.env; el README explica cada valor. - Instalaciones reproducibles. Un
package-lock.jsoncon las versiones exactas de los paquetes y un.nvmrcpara Node.js 26.
Lo que no incluye
- Sin correos electrónicos. No hay verificación de correo ni restablecimiento de contraseña.
- Sin inicio de sesión con redes sociales, autenticación de dos factores ni llaves de acceso.
- Sin páginas protegidas. Todas las páginas son públicas; el encabezado muestra la sesión.
- Sin alojamiento. La app se ejecuta en tu equipo. Desplegarla depende de ti.
Ponla en marcha en seis pasos
- Instala Node.js 26 LTS e inicia Docker Desktop.
- Descomprime la descarga y abre una terminal en su carpeta.
- Ejecuta
npm install. - Copia
.env.examplecomo.env. Ejecutanpx auth@latest secrety pega en.envla línea que muestra. - Ejecuta
docker compose up -d, despuésnpx auth@latest migrate, y respondey. - Ejecuta
npm run dev, abrehttp://localhost:3000y haz clic en Sign up.
Cada paso, con capturas de pantalla: How to Set Up and Run Next.js Authentication with Better Auth and PostgreSQL (se abre en una pestaña nueva) (en inglés).
Aprende las ideas que hay detrás del código en el tutorial gratuito Better Auth Tutorial for Beginners (se abre en una pestaña nueva) (en inglés).
Better Auth, Next.js, PostgreSQL, Docker y los demás nombres mencionados son marcas comerciales de sus respectivos propietarios. Este proyecto no está afiliado a Better Auth, Inc. ni a Vercel, ni cuenta con su respaldo.
Serie de tutoriales gratuita
Better Auth Tutorial for Beginners
¿Prefieres aprender construyéndolo? Esta guía gratuita y paso a paso en nuestro blog muestra cómo se hace el proyecto.
Qué te llevas
Todo lo que hay en el archivo, de un vistazo.
- La versión 1.0.0 del código fuente completo de la app de Next.js
- Páginas de registro e inicio de sesión con mensajes de error claros
- Un encabezado que muestra quién ha iniciado sesión, con un botón Sign out
- Better Auth 1.7 configurado con PostgreSQL, con su controlador de ruta y su cliente de React
- Un archivo de Docker Compose que ejecuta PostgreSQL 18 en tu equipo
- Una comprobación de ajustes que detiene la app con un mensaje claro cuando falta un ajuste o no es válido
- Cinco pruebas para la comprobación de ajustes
- Un archivo de ajustes de ejemplo, un archivo de bloqueo de paquetes y un archivo .nvmrc
- Un README con los requisitos, la instalación, todos los ajustes, los scripts y la solución de problemas
Construido con
Los entornos y las versiones exactos con los que se creó y se probó.
- 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
Qué contiene el archivo
El árbol de carpetas que obtienes al descomprimirlo.
nextjs-authentication-better-auth-postgresql/
- .env.example
- .gitattributes
- .gitignore
- .nvmrc
- AGENTS.md
- README.md
- app/
- api/
- auth/
- [...all]/
- route.ts
- [...all]/
- auth/
- favicon.ico
- globals.css
- layout.tsx
- page.tsx
- sign-in/
- page.tsx
- sign-up/
- page.tsx
- api/
- 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
Qué necesita de ti
Las cuentas y los servicios que espera encontrar, para que nada te sorprenda.
- Node.js 26 LTS y npm
- Docker con Docker Compose: Docker Desktop en macOS o Windows, o Docker Engine en Linux. Docker Desktop es gratuito para uso personal y pequeñas empresas; las organizaciones más grandes necesitan una suscripción de pago
- Los puertos 3000 (la app) y 5435 (la base de datos) libres en tu equipo
- Ninguna otra cuenta, clave de API ni servicio de pago: todo se ejecuta en tu equipo
Versiones
Todas las versiones hasta ahora, de la más reciente a la más antigua.
1.0.0Más reciente
Primera versión del código fuente completo.
- Registro, inicio y cierre de sesión con correo electrónico y contraseña mediante Better Auth 1.7.26 en Next.js 16.4.6.
- PostgreSQL 18 en Docker Compose, con las tablas de Better Auth creadas con un solo comando.
- Una comprobación de ajustes al arrancar, con cinco pruebas.
Source Code Licence
Qué puedes hacer con él
What you may and may not do with the source code you buy.
Leer la licencia completa
- 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.
- 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.
- 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.
- 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.
- 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.
- 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.
- 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.
- 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.
- 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.
- 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.
Next.js Authentication with Better Auth and PostgreSQL
- 199 INR+ GST, 234,82 INR en total
- 3 US$