Configurar Husky y lint-staged para Next.js

Guía práctica para configurar pre-commit con Husky y lint-staged en Next.js con pnpm en Windows: instalación, reglas ESLint y Prettier, hook de pre-commit, depuración y buenas prácticas de CI/CD

4 sept 2025 • 3 min read • Q2BSTUDIO Team

Inteligencia-Artificial-

Configuración de pre-commit con Husky y lint-staged para Next.js

En Q2BSTUDIO potenciamos la calidad de código y la velocidad de entrega en proyectos de aplicaciones a medida y software a medida con flujos de trabajo automatizados. A continuación encontrarás una guía clara para configurar husky y lint-staged en un proyecto Next.js usando pnpm en Windows, con énfasis en buenas prácticas que facilitan la escalabilidad y el mantenimiento.

Requisitos previos

Proyecto Next.js ya creado. Conocimientos básicos de git. Uso de pnpm en Windows. Familiaridad con husky, lint-staged, eslint y prettier.

Instalación de dependencias

Ejecuta en la raíz del proyecto: pnpm add --save-dev husky prettier lint-staged eslint

Añade el script prepare

Abre package.json y agrega en scripts la tarea prepare con valor husky para que se instale automáticamente tras pnpm install.

Inicializa husky

Ejecuta: pnpm exec husky init

Configura el hook pre-commit

Edita el archivo .husky/pre-commit y añade la instrucción: pnpm exec lint-staged

Configura lint-staged

En package.json agrega la sección lint-staged con estas reglas

Para archivos js jsx ts tsx ejecutar primero eslint --max-warnings=0 --fix y después prettier --write

Para archivos json md css scss html yml yaml ejecutar prettier --write

Esta configuración hace que solo se analicen y corrijan los archivos que vas a commitear, acelerando el flujo de trabajo sin perder calidad.

Prueba del pre-commit

Edita cualquier archivo y añade por ejemplo: const a = 0;

Ejecuta: git add . y luego git commit -m Test commit

El commit debería fallar porque a no se usa y la regla eslint con max-warnings en 0 evita confirmar cambios con advertencias. Corrige el código o ajusta la regla para continuar.

Depuración de lint-staged

Si algo no se comporta como esperas, prueba con salida detallada: pnpm dlx lint-staged --verbose

También puedes validar la configuración sin crear un commit: pnpm dlx lint-staged --debug

Notas y buenas prácticas

Integra en CI CD tareas como pnpm run lint y pnpm run format o format:write para asegurar consistencia. Mantén versiones de Node y pnpm alineadas en el equipo para evitar diferencias de formateo. Considera combinar esta configuración con pruebas unitarias y de integración para bloquear commits que rompan la build.

Cómo encaja esto con el desarrollo profesional

En Q2BSTUDIO diseñamos pipelines que unifican calidad, seguridad y despliegue continuo para proyectos de software a medida. Desde la base del repositorio hasta la puesta en producción, nuestros equipos implementan estándares sólidos que reducen defectos, mejoran la mantenibilidad y aceleran el time to market.

Si estás planificando un proyecto de aplicaciones a medida te recomendamos descubrir cómo trabajamos en desarrollo multiplataforma aquí: software a medida y aplicaciones a medida. Y si buscas elevar tu eficiencia con automatización del ciclo de vida del software, orquestación de pipelines y herramientas devops, visita nuestra página de automatización de procesos.

Más allá del control de calidad del código, acompañamos a empresas con soluciones de inteligencia artificial ia para empresas y agentes IA, ciberseguridad y pentesting, servicios cloud aws y azure, y servicios inteligencia de negocio con power bi, integrando estas capacidades en tus productos y procesos para obtener valor medible desde el primer sprint.

Resumen rápido

Instala husky y lint-staged con pnpm. Añade script prepare y ejecuta pnpm exec husky init. Configura .husky pre-commit para correr pnpm exec lint-staged. Define reglas de eslint y prettier para archivos en staging. Prueba con un commit y depura con opciones verbose o debug. Lleva la misma disciplina a tu CI CD.

Escrito por Q2BSTUDIO especialistas en desarrollo de software, inteligencia artificial, ciberseguridad, servicios cloud aws y azure, servicios inteligencia de negocio y power bi.

A BREAK?

Play for a moment before you go

OUR SERVICES

How we can help you

Artificial intelligence

AI agents, chatbots, and intelligent assistants that automate tasks and serve your customers 24/7 to improve the efficiency of your business.

More info

Software Development

Web, mobile, and desktop applications, intranets, e-commerce, SaaS, and management platforms designed for your company's specific needs.

More info

Cloud services

Migration, infrastructure, managed hosting, high availability, and security on Microsoft Azure and Amazon Web Services to help your business scale without limits.

More info

Cybersecurity and pentesting

Security audits, penetration testing and protection of applications, data and infrastructure on-premise and cloud, with ethical hacking and regulatory compliance.

More info

Business Intelligence

Dashboards and data analysis with Power BI: we integrate your sources, design dashboards and KPIs and turn your data into decisions.

More info

Process automation

We automate repetitive tasks and connect your applications with n8n, Power Automate, Make, and RPA, eliminating manual work and increasing productivity.

More info

Training for Companies

We train your teams in technology with criteria: web development, databases, Git, best practices and security, automation with n8n, artificial intelligence for companies and creation of AI solutions with Azure AI Foundry.

More info

Code Auditing

We audit the code that you, your team or an AI create: we tell you what is good and what to improve, we secure it and make it ready for production, web or app.

More info

AI Image Generation

We create for you the images that your business needs with artificial intelligence: product, networks, advertising, illustration and avatars. You tell us what you want and we deliver it ready to use.

More info

AI Video Generation

We create videos with artificial intelligence for you: promotional, networking, virtual presenters, dubbing and animations. You tell us the idea and we will deliver it assembled and ready to publish.

More info

AI Conversational Avatars

We create conversational avatars with AI – digital humans with a face and voice – that serve your customers and teams with the knowledge of your company, on your website, interactive monitors, WhatsApp or Teams.

More info

Online Marketing and AI

Google Ads, Meta Ads, LinkedIn Ads and AI Engine Positioning (GEO/AEO): we attract customers and make your brand appear where they search for you, also on ChatGPT, Gemini and Perplexity.

More info

Do you have a project in mind?

Tell us your vision and we'll turn it into a software solution. Whatever the scope, we make your idea real.

Live Chat