Volver al Blog
SoftwareWebAutomatización

Portal de Clientes Seguro Conectado a Google Drive y Google Sheets con Next.js 15

Brayan Developer
6 min de lectura
Portal de Clientes Seguro Conectado a Google Drive y Google Sheets con Next.js 15
Construye un portal web privado para clientes con Next.js 15, autenticación sin contraseña (Magic Links) y sincronización segura con Google Drive y Google Sheets.

Para agencias, estudios contables, consultoras y empresas de servicios B2B, mantener a los clientes informados sobre el estado de sus proyectos, cotizaciones, entregables y facturas suele implicar decenas de correos electrónicos y mensajes dispersos en WhatsApp. Sin embargo, invertir en licencias costosas de CRMs corporativos como Salesforce o HubSpot suele ser sobredimensionado. La solución más eficiente consiste en desarrollar un Portal de Clientes a medida con Next.js 15, alimentado directamente por las carpetas de Google Drive y hojas de Google Sheets que el equipo operativo ya utiliza a diario.

Portada

Arquitectura del Portal: Seguridad sin Exposición de Credenciales#

Un error frecuente al integrar Google Workspace con interfaces web es exponer claves de API o enlaces públicos de Drive. En nuestra arquitectura, el portal web actúa como una capa de seguridad intermedia (BFF - Backend for Frontend) con cuentas de servicio de Google Cloud (Google Service Account), de forma que el cliente final solo puede acceder a sus propios documentos autorizados:

[Cliente Autenticado (Magic Link)]
                │
                │ HTTPS (Sesión Cifrada JWT / HttpOnly)
                ▼
      [Portal Web Next.js 15]
      ├── Server Components (RSC)
      └── Service Account Auth (Google Cloud IAM)
                │
    ┌───────────┴───────────┐
    │                       │
    ▼                       ▼
[Google Sheets API]   [Google Drive API]
- Estado de Proyecto  - Entregables PDF
- Cotizaciones        - Reportes y Facturas
- Cronograma de Hitos - Carpetas Privadas

Para ofrecer una experiencia sin fricción y de alta seguridad, el cliente ingresa su correo corporativo y recibe un enlace de acceso de un solo uso (Magic Link) con expiración de 15 minutos:

// app/actions/auth.ts
"use server";

import crypto from "crypto";
import { Resend } from "resend";
import { cookies } from "next/headers";
import { signSessionToken } from "@/lib/auth/jwt";

const resend = new Resend(process.env.RESEND_API_KEY);

export async function requestMagicLinkAction(email: string) {
  // 1. Validar que el correo exista en la base de clientes de Google Sheets
  const isRegisteredClient = await verifyClientInSheets(email);
  if (!isRegisteredClient) {
    return { success: false, error: "Correo no registrado en el sistema." };
  }

  // 2. Generar token criptográfico con TTL de 15 minutos
  const token = crypto.randomBytes(32).toString("hex");
  const expiresAt = Date.now() + 15 * 60 * 1000;

  // 3. Guardar temporalmente en Redis
  await saveAuthToken(token, { email, expiresAt });

  // 4. Enviar correo seguro
  const magicUrl = `${process.env.NEXT_PUBLIC_APP_URL}/auth/verify?token=${token}`;

  await resend.emails.send({
    from: "Portal Clientes <[email protected]>",
    to: email,
    subject: "Tu enlace de acceso al Portal de Clientes",
    html: `<p>Haz clic en el siguiente enlace para ingresar a tu espacio privado:</p>
           <a href="${magicUrl}" style="padding: 12px 24px; background: #0284c7; color: white; border-radius: 6px; text-decoration: none;">Ingresar al Portal</a>`,
  });

  return { success: true, message: "Enlace enviado a tu bandeja de entrada." };
}

Conexión Segura con Google Drive API para Descarga de Archivos#

Mediante una Service Account autorizada con permisos de lectura exclusivos, el servidor de Next.js lista y genera URLs firmadas temporales para los archivos de la carpeta del cliente:

// lib/google/drive.ts
import { google } from "googleapis";

const auth = new google.auth.GoogleAuth({
  credentials: {
    client_email: process.env.GOOGLE_SERVICE_ACCOUNT_EMAIL,
    private_key: process.env.GOOGLE_SERVICE_ACCOUNT_KEY?.replace(/\\n/g, "\n"),
  },
  scopes: ["https://www.googleapis.com/auth/drive.readonly"],
});

const drive = google.drive({ version: "v3", auth });

export interface ClientDocument {
  id: string;
  name: string;
  mimeType: string;
  size?: string;
  modifiedTime?: string;
}

export async function getClientDocuments(folderId: string): Promise<ClientDocument[]> {
  try {
    const response = await drive.files.list({
      q: `'${folderId}' in parents and trashed = false`,
      fields: "files(id, name, mimeType, size, modifiedTime, webViewLink)",
      orderBy: "modifiedTime desc",
    });

    return (response.data.files || []).map((file) => ({
      id: file.id!,
      name: file.name!,
      mimeType: file.mimeType!,
      size: file.size ? `${(Number(file.size) / (1024 * 1024)).toFixed(2)} MB` : undefined,
      modifiedTime: file.modifiedTime || undefined,
    }));
  } catch (error) {
    console.error("Error al obtener archivos de Google Drive:", error);
    return [];
  }
}

Sincronización en Tiempo Real del Estado de Proyectos con Google Sheets#

El equipo interno gestiona el avance, las fechas de entrega y los comentarios en una hoja de Google Sheets. Next.js consume los datos a través de Server Components con revalidación bajo demanda (On-Demand ISR):

// lib/google/sheets.ts
import { google } from "googleapis";

const sheets = google.sheets({ version: "v4", auth });

export interface ProjectMilestone {
  id: string;
  title: string;
  status: "Pendiente" | "En Progreso" | "Completado";
  deliveryDate: string;
  notes: string;
}

export async function getClientMilestones(spreadsheetId: string, sheetName: string): Promise<ProjectMilestone[]> {
  const response = await sheets.spreadsheets.values.get({
    spreadsheetId,
    range: `${sheetName}!A2:E`,
  });

  const rows = response.data.values || [];

  return rows.map((row) => ({
    id: row[0] || "",
    title: row[1] || "",
    status: row[2] || "Pendiente",
    deliveryDate: row[3] || "",
    notes: row[4] || "",
  }));
}

Interfaz de Dashboard React con Server Components#

Renderizado ultra-rápido en Next.js sin renderizado pesado en cliente:

// app/dashboard/page.tsx
import { getSession } from "@/lib/auth/session";
import { getClientDocuments } from "@/lib/google/drive";
import { getClientMilestones } from "@/lib/google/sheets";
import { redirect } from "next/navigation";

export default async function DashboardPage() {
  const session = await getSession();
  if (!session) redirect("/login");

  const [documents, milestones] = await Promise.all([
    getClientDocuments(session.driveFolderId),
    getClientMilestones(process.env.PROJECTS_SPREADSHEET_ID!, session.clientCode),
  ]);

  return (
    <main className="max-w-6xl mx-auto p-6 space-y-8">
      <header className="border-b pb-4">
        <h1 className="text-2xl font-bold text-slate-900">Bienvenido, {session.clientName}</h1>
        <p className="text-slate-600">Espacio privado de seguimiento y documentación oficial.</p>
      </header>

      {/* Sección de Hitos y Avance */}
      <section className="bg-white rounded-xl shadow-sm border p-6">
        <h2 className="text-lg font-semibold mb-4">Cronograma de Entregables</h2>
        <div className="space-y-3">
          {milestones.map((m) => (
            <div key={m.id} className="flex justify-between items-center p-3 border rounded-lg">
              <div>
                <p className="font-medium text-slate-800">{m.title}</p>
                <p className="text-sm text-slate-500">Fecha estimada: {m.deliveryDate}</p>
              </div>
              <span className={`px-3 py-1 rounded-full text-xs font-semibold ${
                m.status === "Completado" ? "bg-emerald-100 text-emerald-800" :
                m.status === "En Progreso" ? "bg-amber-100 text-amber-800" : "bg-slate-100 text-slate-800"
              }`}>
                {m.status}
              </span>
            </div>
          ))}
        </div>
      </section>

      {/* Sección de Documentos Google Drive */}
      <section className="bg-white rounded-xl shadow-sm border p-6">
        <h2 className="text-lg font-semibold mb-4">Documentos y Entregables</h2>
        <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
          {documents.map((doc) => (
            <a
              key={doc.id}
              href={`/api/documents/${doc.id}/download`}
              className="flex items-center justify-between p-4 border rounded-lg hover:border-sky-500 transition-colors"
            >
              <div className="truncate pr-4">
                <p className="font-medium text-slate-800 truncate">{doc.name}</p>
                <p className="text-xs text-slate-500">{doc.size || "Archivo"}</p>
              </div>
              <span className="text-sky-600 text-sm font-semibold">Descargar</span>
            </a>
          ))}
        </div>
      </section>
    </main>
  );
}

Ventajas para Negocios y Empresas#

  1. Cero Coste de Licencias por Usuario: A diferencia de las plataformas SaaS tradicionales que cobran entre $30 y $100 USD mensuales por cada cliente o agente, el portal funciona con tu suscripción existente de Google Workspace.
  2. Control Total de la Marca: Interfaz 100% personalizada con los colores, dominio y logotipo corporativo de tu empresa.
  3. Flujo de Trabajo Familiar: El equipo comercial y operativo continúa trabajando en sus hojas de cálculo y carpetas compartidas de siempre sin curva de aprendizaje.

Conclusión#

Integrar un portal web moderno en Next.js 15 con Google Drive y Google Sheets permite profesionalizar la atención corporativa, proteger documentos confidenciales y automatizar la comunicación con clientes a una fracción del costo habitual.

¿Deseas implementar un portal privado de clientes o integrar Google Workspace en la infraestructura digital de tu empresa? Revisa nuestras soluciones en Desarrollo de Software y Automatización o escríbenos directamente.

Etiquetas
Portal de ClientesGoogle SheetsGoogle Drive APINext.jsCRMGoogle Workspace
Compartir:XLinkedInWhatsApp

¿Te gustaría profundizar en estos temas?

Aprende sobre desarrollo de software, apps a medida, automatizaciones con N8N, Next.js y Cloud con casos reales.

Hablemos