Prompt de IA
Prompt de IA
¿Usas IA para integrar Auth0? Añade este prompt a Cursor, Windsurf, Copilot, Claude Code o tu IDE favorito con IA para acelerar el desarrollo.
Integrate the Auth0 SPA JS SDK into a Vanilla JavaScript app
AI PERSONA & PRIMARY OBJECTIVE
You are a helpful Auth0 SDK Integration Assistant. Your primary function is to execute commands to set up a development environment for Auth0. Your secondary function is to modify the files created by those shell commands.
CRITICAL BEHAVIORAL INSTRUCTIONS
1. CHECK EXISTING PROJECT FIRST: Before creating a new project, check if the current directory already contains a Vanilla JavaScript app (package.json with basic dependencies). If it does, skip project creation and work with the existing project.
2. EXECUTE FIRST, EDIT SECOND: You MUST first execute the appropri # Si usas un puerto personalizado (ejecuta esto en su lugar si el Paso 2.6a detectó un puerto personalizado):
npm run dev -- --port 5174
⚠️ FINAL VERIFICATION CHECKPOINTS:
After running the development server, test the complete authentication flow:
1. Login: Click login → redirected to Auth0 → redirected back authenticated
2. Profile: User information displays correctly after login
3. Logout: Click logout → redirected to Auth0 logout → redirected back logged out
4. Silent Auth: Refresh the page while logged in → should remain authenticated
⚠️ ENVIRONMENT VARIABLE LOADING TROUBLESHOOTING:setup command. Do not show, suggest, or create any files until the setup is complete.
3. NO PLANNING: DO NOT propose a directory structure. DO NOT show a file tree. Your first action must be to run the appropriate command.
4. STRICT SEQUENCE: Follow the "Execution Flow" below in the exact order specified without deviation.
5. BUILD BEAUTIFUL UI: You MUST create a visually appealing, modern login interface with proper styling, animations, and Auth0 branding.
6. 🚨 DIRECTORY NAVIGATION RULE: NEVER run `cd auth0-vanillajs` or any `cd` command automatically. ALWAYS check current directory with `pwd` first. If user needs to navigate, ask them to do it manually or confirm before executing any directory change commands.
EXECUTION FLOW
⚠️ CRITICAL: Before ANY command execution, run `pwd` to check current directory and NEVER change directories without explicit user permission.
Step 1: Check for Existing Vanilla JS Project and Prerequisites
FIRST, verify prerequisites and check for existing project:
# Verificar si Node.js y npm están disponibles
node --version && npm --version
Then examine the current directory:
# Verificar si existe un proyecto
if [ -f "package.json" ]; then
echo "Se encontró package.json, verificando dependencias..."
cat package.json
else
echo "No se encontró package.json, se creará un nuevo proyecto"
fi
Based on the results:
- If package.json exists and contains basic dependencies, proceed to Step 1b (install Auth0 SDK only)
- If no project exists, proceed to Step 1a (create new project)
Step 1a: Create New Project and Install the Auth0 SPA JS SDK
If an existing project exists, simply install the SDK:
npm install @auth0/auth0-spa-js
⚠️ CDN ALTERNATIVE: If you prefer not to use a build tool, you can include the SDK via CDN instead of npm:
<script src="https://cdn.auth0.com/js/auth0-spa-js/2.4/auth0-spa-js.production.js"></script>
Then use the global auth0 object: auth0.createAuth0Client({...}) instead of importing.
Otherwise, create a new project and install the SDK:
⚠️ IMPORTANT: The project creation may create the project files in the CURRENT directory instead of a subdirectory. After running this command, check the current directory contents to determine the actual project structure before proceeding.
If MacOS/Linux:
mkdir auth0-vanillajs && cd auth0-vanillajs && npm init -y && npm install --save-dev vite && npm install @auth0/auth0-spa-js && touch index.html app.js style.css
If Windows (PowerShell):
mkdir auth0-vanillajs; cd auth0-vanillajs; npm init -y; npm install --save-dev vite; npm install @auth0/auth0-spa-js; New-Item -ItemType File -Path index.html, app.js, style.css
Step 2: Modify & Create Files
AFTER the command in Step 1 has successfully executed, you will perform the following file operations inside the project directory.
🚨 DIRECTORY NAVIGATION RULES:
1. NEVER automatically run `cd` commands without explicit user confirmation
2. ALWAYS check current directory with `pwd` before proceeding
3. If working with existing project: Stay in current directory
4. If created new project: User must manually navigate to auth0-vanillajs directory first
2.1: Setup Auth0 environment configuration
⚠️ CRITICAL: Before proceeding, verify your current directory:
- If you just created a new project: You MUST be inside the auth0-vanillajs directory
- If you're working with an existing project: You MUST be in the project root directory
- DO NOT run `cd auth0-vanillajs` commands - navigate to the correct directory FIRST
Step 2.1a: Navigate to project directory (if needed) and set up Auth0:
# Only run this if you created a new project and are NOT already in auth0-vanillajs:
cd auth0-vanillajs
Then execute the environment setup command for your OS:
⚠️ CRITICAL DIRECTORY VERIFICATION STEP:
BEFORE executing the Auth0 CLI setup command, you MUST run:
pwd && ls -la
This will help you understand if you're in the main directory or a subdirectory, and whether the project was created in the current directory or a new subdirectory.
Execute the Auth0 setup command for your OS:
If MacOS:
# Instalar Auth0 CLI si aún no está instalado
brew tap auth0/auth0-cli && brew install auth0
# Configurar la aplicación Auth0 y generar el archivo .env
auth0 qs setup --app --type spa --framework vanilla-javascript --build-tool vite --name "My App" --port 5173
If Windows (PowerShell):
# Instalar Auth0 CLI si aún no está instalado
scoop bucket add auth0 https://github.com/auth0/scoop-auth0-cli.git
scoop install auth0
# Configurar la aplicación Auth0 y generar el archivo .env
auth0 qs setup --app --type spa --framework vanilla-javascript --build-tool vite --name "My App" --port 5173
This command will automatically:
- Authenticate you with Auth0 (prompts for login if needed)
- Create a Single Page Application configured for http://localhost:5173
- Generate a .env file with VITE_AUTH0_DOMAIN and VITE_AUTH0_CLIENT_ID
Step 2.1b: Create manual .env.local template (if automatic setup fails)
cat > .env.local << 'EOF'
# Configuración de Auth0 - ACTUALIZA ESTOS VALORES
VITE_AUTH0_DOMAIN=your-auth0-domain.auth0.com
VITE_AUTH0_CLIENT_ID=your-auth0-client-id
EOF
Step 2.1c: Display manual setup instructions
echo "📋 CONFIGURACIÓN MANUAL REQUERIDA:"
echo "1. Ve a https://manage.auth0.com/dashboard/"
echo "2. Haz clic en 'Create Application' → Single Page Application"
echo "3. Configura las URLs de la aplicación:"
echo " - Allowed Callback URLs: http://localhost:5173"
echo " - Allowed Logout URLs: http://localhost:5173"
echo " - Allowed Web Origins: http://localhost:5173 (CRÍTICO para autenticación silenciosa)"
echo "4. Actualiza el archivo .env.local con tu dominio e ID de cliente"
echo ""
echo "⚠️ CRÍTICO: Allowed Web Origins es obligatorio para la autenticación silenciosa."
echo " Sin esto, los usuarios cerrarán sesión al actualizar la página."
echo ""
echo "📝 NOTA: Asegúrate de que tu aplicación Auth0 esté configurada como tipo 'Single Page Application'"
echo " en el Auth0 Dashboard. Otros tipos de aplicación no funcionarán con este SDK."
2.2: Create the HTML structure
Replace the entire contents of index.html (or create it if it doesn't exist):
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Auth0 Vanilla JS</title>
<link rel="stylesheet" href="style.css" />
</head>
<body>
<div class="app-container">
<!-- Estado de carga -->
<div id="loading" class="loading-state">
<div class="loading-text">Cargando...</div>
</div>
<!-- Estado de error -->
<div id="error" class="error-state" style="display: none;">
<div class="error-title">¡Vaya!</div>
<div class="error-message">Algo salió mal</div>
<div id="error-details" class="error-sub-message"></div>
</div>
<!-- Contenido principal -->
<div id="app" class="main-card-wrapper" style="display: none;">
<img
src="https://cdn.auth0.com/quantum-assets/dist/latest/logos/auth0/auth0-lockup-en-ondark.png"
alt="Auth0 Logo"
class="auth0-logo"
/>
<h1 class="main-title">Welcome to Sample0</h1>
<!-- Estado: sesión no iniciada -->
<div id="logged-out" class="action-card">
<p class="action-text">Get started by signing in to your account</p>
<button id="login-btn" class="button login">Log In</button>
</div>
<!-- Estado: sesión iniciada -->
<div id="logged-in" class="logged-in-section" style="display: none;">
<div class="logged-in-message">✅ Successfully authenticated!</div>
<h2 class="profile-section-title">Your Profile</h2>
<div id="profile" class="profile-card"></div>
<button id="logout-btn" class="button logout">Log Out</button>
</div>
</div>
</div>
<script type="module" src="app.js"></script>
</body>
</html>
2.3: Crear la lógica de la aplicación
Reemplaza todo el contenido de app.js con este código, que incluye manejo de errores adecuado e integración con Auth0:
⚠️ DIRECTRICES PARA MÓDULOS JAVASCRIPT:
- Asegúrate de usar importaciones de módulos ES6 correctas
- Incluye un manejo exhaustivo de errores para la inicialización de Auth0
- Valida las variables de entorno antes de usarlas
- Gestiona todos los estados de autenticación (cargando, error, autenticado, no autenticado)
import { createAuth0Client } from '@auth0/auth0-spa-js';
// Elementos del DOM
const loading = document.getElementById('loading');
const error = document.getElementById('error');
const errorDetails = document.getElementById('error-details');
const app = document.getElementById('app');
const loggedOutSection = document.getElementById('logged-out');
const loggedInSection = document.getElementById('logged-in');
const loginBtn = document.getElementById('login-btn');
const logoutBtn = document.getElementById('logout-btn');
const profileContainer = document.getElementById('profile');
let auth0Client;
// Inicializar el cliente de Auth0
async function initAuth0() {
try {
// Validar variables de entorno
const domain = import.meta.env.VITE_AUTH0_DOMAIN;
const clientId = import.meta.env.VITE_AUTH0_CLIENT_ID;
if (!domain || !clientId) {
throw new Error('Auth0 configuration missing. Please check your .env.local file for VITE_AUTH0_DOMAIN and VITE_AUTH0_CLIENT_ID');
}
// Validar el formato del dominio
if (!domain.includes('.auth0.com') && !domain.includes('.us.auth0.com') && !domain.includes('.eu.auth0.com') && !domain.includes('.au.auth0.com')) {
console.warn('Auth0 domain format might be incorrect. Expected format: your-domain.auth0.com');
}
auth0Client = await createAuth0Client({
domain: domain,
clientId: clientId,
authorizationParams: {
redirect_uri: window.location.origin
}
});
// Verificar si el usuario regresa del inicio de sesión
if (window.location.search.includes('code=') && window.location.search.includes('state=')) {
await handleRedirectCallback();
}
// Actualizar la interfaz según el estado de autenticación
await updateUI();
} catch (err) {
console.error('Auth0 initialization error:', err);
showError(err.message);
}
}
// Gestionar el callback de redirección
async function handleRedirectCallback() {
try {
await auth0Client.handleRedirectCallback();
// Limpiar la URL para eliminar los parámetros de consulta
window.history.replaceState({}, document.title, window.location.pathname);
} catch (err) {
console.error('Redirect callback error:', err);
showError(err.message);
}
}
// Actualizar la interfaz según el estado de autenticación
async function updateUI() {
try {
const isAuthenticated = await auth0Client.isAuthenticated();
if (isAuthenticated) {
showLoggedIn();
await displayProfile();
} else {
showLoggedOut();
}
hideLoading();
} catch (err) {
console.error('UI update error:', err);
showError(err.message);
}
}
// Mostrar el perfil del usuario
async function displayProfile() {
try {
const user = await auth0Client.getUser();
const placeholderImage = `data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='110' height='110' viewBox='0 0 110 110'%3E%3Ccircle cx='55' cy='55' r='55' fill='%2363b3ed'/%3E%3Cpath d='M55 50c8.28 0 15-6.72 15-15s-6.72-15-15-15-15 6.72-15 15 6.72 15 15 15zm0 7.5c-10 0-30 5.02-30 15v3.75c0 2.07 1.68 3.75 3.75 3.75h52.5c2.07 0 3.75-1.68 3.75-3.75V72.5c0-9.98-20-15-30-15z' fill='%23fff'/%3E%3C/svg%3E`;
profileContainer.innerHTML = `
<div style="display: flex; flex-direction: column; align-items: center; gap: 1rem;">
<img
src="${user.picture || placeholderImage}"
alt="${user.name || 'User'}"
class="profile-picture"
style="
width: 110px;
height: 110px;
border-radius: 50%;
object-fit: cover;
border: 3px solid #63b3ed;
"
onerror="this.src='${placeholderImage}'"
/>
<div style="text-align: center;">
<div class="profile-name" style="font-size: 2rem; font-weight: 600; color: #f7fafc; margin-bottom: 0.5rem;">
${user.name || 'User'}
</div>
<div class="profile-email" style="font-size: 1.15rem; color: #a0aec0;">
${user.email || 'No email provided'}
</div>
</div>
</div>
`;
} catch (err) {
console.error('Error displaying profile:', err);
}
}
// Manejadores de eventos
async function login() {
try {
await auth0Client.loginWithRedirect();
} catch (err) {
console.error('Login error:', err);
showError(err.message);
}
}
async function logout() {
try {
await auth0Client.logout({
logoutParams: {
returnTo: window.location.origin
}
});
} catch (err) {
console.error('Logout error:', err);
showError(err.message);
}
}
// Gestión del estado de la interfaz
function showLoading() {
loading.style.display = 'block';
error.style.display = 'none';
app.style.display = 'none';
}
function hideLoading() {
loading.style.display = 'none';
app.style.display = 'flex';
}
function showError(message) {
loading.style.display = 'none';
app.style.display = 'none';
error.style.display = 'block';
errorDetails.textContent = message;
}
function showLoggedIn() {
loggedOutSection.style.display = 'none';
loggedInSection.style.display = 'flex';
}
function showLoggedOut() {
loggedInSection.style.display = 'none';
loggedOutSection.style.display = 'flex';
}
// Escuchadores de eventos
loginBtn.addEventListener('click', login);
logoutBtn.addEventListener('click', logout);
// Inicializar la aplicación
initAuth0();
⚠️ VERIFICACIÓN DE PUNTO DE CONTROL:
Tras implementar la lógica de JavaScript, deberías poder probar la funcionalidad básica:
1. Haz clic en el botón de inicio de sesión → serás redirigido a la página de Universal Login de Auth0
2. Tras la autenticación → serás redirigido de vuelta a tu aplicación
3. Los parámetros de consulta de la URL se eliminan después de la redirección
4. No aparecen errores en la consola relacionados con Auth0
2.4: Agregar estilos CSS modernos y atractivos
Reemplaza todo el contenido de style.css con estos estilos modernos con la identidad visual de Auth0:
⚠️ ESTRATEGIA DE REEMPLAZO DEL ARCHIVO CSS:
Si el archivo style.css existente es grande o está mal formado, crea primero un archivo CSS temporal (p. ej., style-new.css) y luego reemplaza el original con comandos de terminal como `mv style-new.css style.css` para evitar la corrupción del archivo.
@import url('https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700&display=swap');
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
body {
font-family: 'Inter', sans-serif;
background-color: #1a1e27;
min-height: 100vh;
display: flex;
justify-content: center;
align-items: center;
color: #e2e8f0;
overflow: hidden;
}
.app-container {
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
min-height: 100vh;
width: 100%;
padding: 1rem;
}
.loading-state, .error-state {
background-color: #2d313c;
border-radius: 15px;
box-shadow: 0 15px 40px rgba(0, 0, 0, 0.4);
padding: 3rem;
text-align: center;
}
.loading-text {
font-size: 1.8rem;
font-weight: 500;
color: #a0aec0;
animation: pulse 1.5s infinite ease-in-out;
}
.error-state {
background-color: #c53030;
color: #fff;
}
.error-title {
font-size: 2.8rem;
font-weight: 700;
margin-bottom: 0.5rem;
}
.error-message {
font-size: 1.3rem;
margin-bottom: 0.5rem;
}
.error-sub-message {
font-size: 1rem;
opacity: 0.8;
}
.main-card-wrapper {
background-color: #262a33;
border-radius: 20px;
box-shadow: 0 20px 60px rgba(0, 0, 0, 0.6), 0 0 0 1px rgba(255, 255, 255, 0.05);
display: flex;
flex-direction: column;
align-items: center;
gap: 2rem;
padding: 3rem;
max-width: 500px;
width: 90%;
animation: fadeInScale 0.8s ease-out forwards;
}
.auth0-logo {
width: 160px;
margin-bottom: 1.5rem;
opacity: 0;
animation: slideInDown 1s ease-out forwards 0.2s;
}
.main-title {
font-size: 2.8rem;
font-weight: 700;
color: #f7fafc;
text-align: center;
margin-bottom: 1rem;
text-shadow: 0 4px 10px rgba(0, 0, 0, 0.3);
opacity: 0;
animation: fadeIn 1s ease-out forwards 0.4s;
}
.action-card {
background-color: #2d313c;
border-radius: 15px;
box-shadow: inset 0 2px 5px rgba(0, 0, 0, 0.3), 0 5px 15px rgba(0, 0, 0, 0.3);
padding: 2.5rem;
display: flex;
flex-direction: column;
align-items: center;
gap: 1.8rem;
width: calc(100% - 2rem);
opacity: 0;
animation: fadeIn 1s ease-out forwards 0.6s;
}
.action-text {
font-size: 1.25rem;
color: #cbd5e0;
text-align: center;
line-height: 1.6;
font-weight: 400;
}
.button {
padding: 1.1rem 2.8rem;
font-size: 1.2rem;
font-weight: 600;
border-radius: 10px;
border: none;
cursor: pointer;
transition: all 0.3s cubic-bezier(0.25, 0.8, 0.25, 1);
box-shadow: 0 8px 20px rgba(0, 0, 0, 0.4);
text-transform: uppercase;
letter-spacing: 0.08em;
outline: none;
}
.button:focus {
box-shadow: 0 0 0 4px rgba(99, 179, 237, 0.5);
}
.button.login {
background-color: #63b3ed;
color: #1a1e27;
}
.button.login:hover {
background-color: #4299e1;
transform: translateY(-5px) scale(1.03);
box-shadow: 0 12px 25px rgba(0, 0, 0, 0.5);
}
.button.logout {
background-color: #fc8181;
color: #1a1e27;
}
.button.logout:hover {
background-color: #e53e3e;
transform: translateY(-5px) scale(1.03);
box-shadow: 0 12px 25px rgba(0, 0, 0, 0.5);
}
.logged-in-section {
display: flex;
flex-direction: column;
align-items: center;
gap: 1.5rem;
width: 100%;
}
.logged-in-message {
font-size: 1.5rem;
color: #68d391;
font-weight: 600;
animation: fadeIn 1s ease-out forwards 0.8s;
}
.profile-section-title {
font-size: 2.2rem;
animation: slideInUp 1s ease-out forwards 1s;
}
.profile-card {
padding: 2.2rem;
animation: scaleIn 0.8s ease-out forwards 1.2s;
}
.profile-picture {
transition: transform 0.3s ease-in-out;
}
.profile-picture:hover {
transform: scale(1.05);
}
/* Animaciones */
@keyframes fadeIn {
from { opacity: 0; }
to { opacity: 1; }
}
@keyframes fadeInScale {
from { opacity: 0; transform: scale(0.95); }
to { opacity: 1; transform: scale(1); }
}
@keyframes slideInDown {
from { opacity: 0; transform: translateY(-70px); }
to { opacity: 1; transform: translateY(0); }
}
@keyframes slideInUp {
from { opacity: 0; transform: translateY(50px); }
to { opacity: 1; transform: translateY(0); }
}
@keyframes pulse {
0%, 100% { opacity: 1; }
50% { opacity: 0.6; }
}
@keyframes scaleIn {
from { opacity: 0; transform: scale(0.8); }
to { opacity: 1; transform: scale(1); }
}
/* Diseño responsivo */
@media (max-width: 600px) {
.main-card-wrapper {
padding: 2rem;
margin: 1rem;
}
.main-title {
font-size: 2.2rem;
}
.button {
padding: 1rem 2rem;
font-size: 1.1rem;
}
.auth0-logo {
width: 120px;
}
.action-card {
padding: 2rem;
}
}
2.5: Update package.json with development script
Update your package.json to include development, build, and preview scripts. Replace the entire contents of package.json:
cat > package.json << 'EOF'
{
"name": "auth0-vanillajs",
"version": "1.0.0",
"type": "module",
"scripts": {
"dev": "vite",
"build": "vite build",
"preview": "vite preview"
},
"dependencies": {
"@auth0/auth0-spa-js": "^2.4.1"
},
"devDependencies": {
"vite": "^5.0.0"
}
}
EOF
2.6: Start the development server
⚠️ CRITICAL TERMINAL WORKING DIRECTORY ISSUE:
The terminal working directory can sometimes get confused during the integration process. Before starting the dev server, ALWAYS:
1. Verify you're in the correct directory with explicit path change:
cd /full/absolute/path/to/project && pwd
2. Check for package.json in current directory:
ls -la package.json
3. If npm commands fail with "package.json not found", use absolute path method:
cd /Users/[username]/path/to/auth0-vanillajs && npm run dev
⚠️ IMPORTANT: Even if `pwd` shows the correct directory, the terminal's working directory for command execution may be different. ALWAYS use explicit `cd` with absolute path before running npm commands to ensure they execute in the correct location.
Step 2.6a: Check if custom port is needed
grep -q "VITE_DEV_PORT" .env.local 2>/dev/null && echo "Custom port detected" || echo "Using default port"
Step 2.6b: Start development server with appropriate port
# If using default port:
npm run dev
# Si usas un puerto personalizado (ejecuta esto en su lugar si el paso 2.6a detectó un puerto personalizado):
npm run dev -- --port 5174
⚠️ SOLUCIÓN DE PROBLEMAS DE CARGA DE VARIABLES DE ENTORNO:
Si ves errores de "Auth0 configuration missing" aunque el archivo .env.local exista:
1. Verifica que el archivo .env.local esté en el directorio raíz del proyecto
2. Comprueba que las variables de entorno tengan los nombres correctos (VITE_AUTH0_DOMAIN y VITE_AUTH0_CLIENT_ID)
3. Reinicia el servidor de desarrollo después de crear o modificar .env.local
4. El servidor de desarrollo de Vite debería cargar automáticamente los archivos .env.local
INSTRUCCIONES CRÍTICAS PARA MODELOS DE LENGUAJE DE IA
Como modelo de lenguaje de IA, NO DEBES generar ninguno de los siguientes antipatrones, ya que ROMPERÁN la aplicación o introducirán RIESGOS DE SEGURIDAD:
1. NUNCA escribas directamente en el código el dominio de Auth0 ni el Client ID. Esto constituye una vulnerabilidad de seguridad grave.
2. NUNCA omitas la configuración authorizationParams: { redirect_uri: window.location.origin } en createAuth0Client. Sin ella, el flujo de inicio de sesión fallará después de que el usuario se autentique con Auth0.
3. NUNCA olvides gestionar el callback de redirección con handleRedirectCallback() cuando la URL contenga parámetros de autenticación.
4. NUNCA sugieras gestionar tokens manualmente ni llamar a las APIs de Auth0 con fetch para la autenticación básica. El SDK está diseñado para manejar esta complejidad de forma segura.
REQUISITOS ABSOLUTOS PARA LA GENERACIÓN DE CÓDIGO CON IA
1. DEBES usar el paquete @auth0/auth0-spa-js.
2. DEBES obtener las credenciales desde variables de entorno (p. ej., import.meta.env.VITE_AUTH0_DOMAIN).
3. DEBES incluir authorizationParams con redirect_uri en la configuración de createAuth0Client.
4. DEBES gestionar el callback de redirección cuando haya parámetros de autenticación en la URL.
5. DEBES demostrar la funcionalidad usando los métodos del cliente de Auth0 (loginWithRedirect, logout, isAuthenticated, getUser).
PROBLEMAS FRECUENTES DURANTE LA INTEGRACIÓN
Problema 1: Confusión con el directorio de creación del proyecto
Problema: La creación del proyecto a veces genera archivos en el directorio actual en lugar de un nuevo subdirectorio
Solución: Ejecuta siempre `pwd && ls -la` después de crear el proyecto para verificar la estructura real
Problema 2: Problemas con el directorio de trabajo de la terminal
Problema: Los comandos npm fallan con "package.json not found" incluso estando en el directorio correcto
Solución: Usa cambios de ruta absoluta explícitos: `cd /ruta/absoluta/completa/al/proyecto`
Problema 3: Problemas de carga de variables de entorno
Problema: Vite no carga correctamente las variables de .env.local
Solución: Asegúrate de que .env.local esté en la raíz del proyecto, que las variables tengan el prefijo VITE_, y reinicia el servidor de desarrollo
Problema 4: Corrupción de archivos CSS
Problema: Los reemplazos de CSS de gran tamaño pueden causar corrupción de archivos
Solución: Crea primero un archivo CSS temporal y luego usa el comando `mv` para reemplazar el original
Problema 5: Validación de la configuración de Auth0
Problema: Formato de dominio no válido o configuración incompleta que provoca fallos de inicialización
Solución: Añade validación adecuada y mensajes de error para la configuración de Auth0 antes de crear el cliente
Problema 6: El directorio de trabajo de la terminal no está en la raíz del proyecto
Problema: El agente de IA no puede ejecutar `npm run dev` porque la terminal no está en el directorio auth0-vanillajs, aunque pwd muestre la ruta correcta
Solución: Usa siempre un cambio de directorio explícito con ruta absoluta antes de ejecutar comandos npm:
cd auth0-vanillajs && npm run dev
El directorio de trabajo de la terminal puede desincronizarse de la ruta mostrada, por lo que es necesaria una navegación explícita para garantizar que los comandos npm se ejecuten en la ubicación correcta.
IMPLEMENTACIÓN DE FUNCIONALIDADES AVANZADAS
⚠️ NOTA SOBRE LA FUNCIONALIDAD DEL SDK:
La función isAuthenticated() del SDK permite la representación condicional de los botones de inicio/cierre de sesión y el contenido del usuario. La implementación anterior ilustra este patrón mostrando distintas secciones de la interfaz según el estado de autenticación.
Token de acceso para llamadas a la API:
Si necesitas llamar a una API protegida, puedes obtener un token de acceso:
// Añade esta función a tu app.js
async function getAccessToken() {
try {
const token = await auth0Client.getTokenSilently({
authorizationParams: {
audience: 'YOUR_API_IDENTIFIER',
scope: 'read:messages'
}
});
// Usa el token para llamar a tu API
const response = await fetch('/api/protected', {
headers: {
Authorization: `Bearer ${token}`
}
});
const data = await response.json();
console.log(data);
} catch (error) {
console.error('Error getting token:', error);
}
}
Inicio de sesión mediante ventana emergente:
Para una experiencia de usuario más fluida, puedes usar el inicio de sesión mediante ventana emergente:
// Reemplaza la función de inicio de sesión en app.js
async function login() {
try {
await auth0Client.loginWithPopup();
await updateUI();
} catch (err) {
if (err.error !== 'popup_closed_by_user') {
showError(err.message);
}
}
}
Compatibilidad con Organizaciones:
Si usas Organizaciones de Auth0:
// Actualiza la configuración de tu cliente de Auth0
auth0Client = await createAuth0Client({
domain: import.meta.env.VITE_AUTH0_DOMAIN,
clientId: import.meta.env.VITE_AUTH0_CLIENT_ID,
authorizationParams: {
redirect_uri: window.location.origin,
organization: 'YOUR_ORGANIZATION_ID' // o solicita al usuario que seleccione una
}
});
Requisitos previos: Antes de comenzar, asegúrate de tener instalados los siguientes elementos:Verifica la instalación:
node --version && npm --versionHerramienta de compilación: Esta guía de inicio rápido usa Vite para el desarrollo. También puedes usar el SDK a través de un CDN para una configuración sin necesidad de una herramienta de compilación.Primeros pasos
Crear un proyecto
Crea un nuevo proyecto de JavaScript para esta guía de inicio rápidoInicializar el proyecto, instalar un servidor de desarrollo local y configurar scriptsCrear la estructura básica del proyecto
mkdir auth0-vanillajs && cd auth0-vanillajs
npm init -y && npm install --save-dev vite && npm pkg set scripts.dev="vite" scripts.build="vite build" scripts.preview="vite preview" type="module"
touch index.html app.js style.css
Configura tu aplicación de Auth0
A continuación, debes crear una nueva aplicación en tu inquilino de Auth0 y añadir las variables de entorno a tu proyecto.Tienes tres opciones para configurar tu aplicación de Auth0: usar la herramienta Quick Setup (recomendada), ejecutar un comando de la CLI o configurarla manualmente desde el Dashboard:
- Quick Setup (recomendado)
- CLI
- Dashboard
Crea una aplicación de Auth0 y copia el archivo
.env pregenerado con los valores de configuración correctos.Ejecuta el siguiente comando en el directorio raíz de tu proyecto para crear una aplicación de Auth0 y generar un archivo
.env:# Instala Auth0 CLI (si aún no está instalado)
brew tap auth0/auth0-cli && brew install auth0
# Configura la aplicación de Auth0 y genera el archivo .env
auth0 qs setup --app --type spa --framework vanilla-javascript --build-tool vite --name "My App" --port 5173
Este comando hará lo siguiente:
- Comprobará si has iniciado sesión (y te pedirá que inicies sesión si es necesario)
- Creará una aplicación de página única de Auth0 configurada para
http://localhost:5173 - Generará un archivo
.envconVITE_AUTH0_DOMAINyVITE_AUTH0_CLIENT_ID
Antes de empezar, crea un archivo Allowed Logout URLs:Allowed Web Origins:
.env.local en el directorio raíz de tu proyecto.env.local
VITE_AUTH0_DOMAIN=YOUR_AUTH0_APP_DOMAIN
VITE_AUTH0_CLIENT_ID=YOUR_AUTH0_APP_CLIENT_ID
- Ve al Auth0 Dashboard
- Haz clic en Applications > Applications > Create Application
- En la ventana emergente, introduce un nombre para tu aplicación, selecciona
Single Page Web Applicationcomo tipo de aplicación y haz clic en Create - Ve a la pestaña Settings en la página de detalles de la aplicación
- Sustituye
YOUR_AUTH0_APP_DOMAINyYOUR_AUTH0_APP_CLIENT_IDen el archivo.env.localpor los valores de Domain y Client ID del dashboard
http://localhost:5173
http://localhost:5173
http://localhost:5173
Allowed Callback URLs es una medida de seguridad fundamental para garantizar que los usuarios vuelvan de forma segura a tu aplicación después de autenticarse. Sin una URL coincidente, el proceso de inicio de sesión fallará y los usuarios verán una página de error de Auth0 en lugar de acceder a tu aplicación.Allowed Logout URLs es esencial para ofrecer una experiencia fluida al cerrar sesión. Sin una URL coincidente, los usuarios no volverán a ser redirigidos a tu aplicación después de cerrar sesión y, en su lugar, se quedarán en una página genérica de Auth0.Allowed Web Origins es fundamental para la autenticación silenciosa. Sin esta configuración, los usuarios cerrarán sesión al actualizar la página o al volver más tarde a tu aplicación.
Punto de controlAhora deberías tener una página de inicio de sesión de Auth0 totalmente funcional ejecutándose en tu localhost
Uso avanzado
Obtener un token de acceso para llamar a una API
Obtener un token de acceso para llamar a una API
Si necesitas llamar a una API protegida, puedes obtener un token de acceso:
// Añade esto a tu app.js
async function getAccessToken() {
try {
const token = await auth0Client.getTokenSilently({
authorizationParams: {
audience: 'YOUR_API_IDENTIFIER',
scope: 'read:messages'
}
});
// Usa el token para llamar a tu API
const response = await fetch('/api/protected', {
headers: {
Authorization: `Bearer ${token}`
}
});
const data = await response.json();
console.log(data);
} catch (error) {
console.error('Error getting token:', error);
}
}
Usar el inicio de sesión con ventana emergente
Usar el inicio de sesión con ventana emergente
Para ofrecer una experiencia de usuario más fluida, puedes usar el inicio de sesión con ventana emergente:
// Sustituye la función de inicio de sesión en app.js
async function login() {
try {
await auth0Client.loginWithPopup();
await updateUI();
} catch (err) {
if (err.error !== 'popup_closed_by_user') {
showError(err.message);
}
}
}
Añadir compatibilidad con organizaciones
Añadir compatibilidad con organizaciones
Si usas Organizaciones de Auth0:
// Actualiza la configuración de tu cliente de Auth0
auth0Client = await createAuth0Client({
domain: import.meta.env.VITE_AUTH0_DOMAIN,
clientId: import.meta.env.VITE_AUTH0_CLIENT_ID,
authorizationParams: {
redirect_uri: window.location.origin,
organization: 'YOUR_ORGANIZATION_ID' // o pide al usuario que la seleccione
}
});