Corrección del ResponseCache de Spatie para Accept-Language

Guía para hacer que Spatie Laravel ResponseCache respete Accept-Language: añade un middleware que derive el sufijo de idioma para la caché, con Vary y verificación.

21 ago 2025 • 3 min read • Q2BSTUDIO Team

Inteligencia-Artificial-

Fixing Spatie Laravel ResponseCache para respetar Accept-Language

Voy a ser honesto. Pocas cosas resultan tan frustrantes como activar un paquete excelente en producción y descubrir que la API ahora responde siempre en el mismo idioma. Esto me pasó recientemente al usar Spatie Laravel ResponseCache: la primera petición se cacheó en inglés y todas las peticiones siguientes, aunque pedían otros idiomas como árabe, recibían la versión en inglés.

El problema radica en que ResponseCache construye la clave de caché a partir del host, la URI normalizada, el método HTTP y un sufijo opcional, pero ignora cabeceras como Accept-Language. Eso convierte una API multilingüe en una que solo habla un idioma en caché.

La solución consiste en añadir un middleware que incluya el idioma en el sufijo de la caché. En lugar de modificar el paquete, se añade un atributo por petición responsecache.cacheNameSuffix con un valor que cambie según el Accept-Language y, opcionalmente, el id del usuario para separar cachés por usuario.

En palabras simples, el flujo es: leer la cabecera Accept-Language, normalizar la primera entrada del listado, combinarla con el id de usuario si procede, y establecer ese valor en attributes bajo responsecache.cacheNameSuffix antes de que Spatie genere la clave de caché. Como toque útil, opcionalmente añadir un header de depuración X-ResponseCache-Suffix para comprobar cuál fue el sufijo usado.

Al registrar este middleware globalmente en Laravel 12 se asegura que todas las respuestas consideren el idioma. Además es importante añadir la cabecera Vary con el valor Accept-Language en las respuestas para que proxies, CDN y balanceadores como AWS ALB no entreguen versiones cacheadas incorrectas a usuarios que piden otro idioma.

No olvides limpiar la caché previa, ya que las entradas antiguas no distinguen idioma. Ejecuta el comando de limpieza de ResponseCache antes de poner en marcha el nuevo middleware para evitar servir contenido en el idioma equivocado.

Para verificar que todo funciona, realiza dos peticiones curl con cabeceras Accept-Language distintas y revisa el header X-ResponseCache-Suffix o el contenido devuelto. Deberías ver sufijos distintos como en y ar o respuestas en el idioma solicitado.

En Q2BSTUDIO, empresa de desarrollo de software y aplicaciones a medida, abordamos este tipo de problemas de forma pragmática y segura. Ofrecemos software a medida, aplicaciones a medida y soluciones escalables que integran las mejores prácticas de cacheo y localización para APIs multilingües. Somos especialistas en inteligencia artificial, ia para empresas y agentes IA, además de servicios de ciberseguridad para proteger datos sensibles y garantizar disponibilidad.

También proporcionamos servicios cloud aws y azure y servicios inteligencia de negocio incluyendo integraciones con power bi para visualización y análisis avanzado. Si necesitas optimizar una API, mejorar la experiencia multilingüe de tus usuarios o implementar agentes IA adaptados a tu negocio, desde Q2BSTUDIO podemos ayudarte con desarrollo a medida, auditorías de ciberseguridad y despliegues en entornos cloud.

Resumen práctico de pasos a seguir sin entrar en código exacto: 1) Crear middleware que lea y normalice Accept-Language. 2) Generar sufijo combinando idioma y opcionalmente id de usuario. 3) Poner ese sufijo en responsecache.cacheNameSuffix. 4) Añadir cabecera Vary con Accept-Language en la respuesta. 5) Limpiar caché previa con la herramienta de ResponseCache. 6) Verificar con peticiones que devuelvan diferentes idiomas.

Si quieres que implementemos esta solución en tu proyecto o necesitas una auditoría completa de rendimiento, localización y seguridad para APIs multilingües, contacta con Q2BSTUDIO. Implementamos soluciones robustas de inteligencia artificial, agentes IA, servicios de inteligencia de negocio y despliegues seguros en AWS y Azure adaptados a tus necesidades.

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