\section{Por qué Vercel + FormaTeX}
Generación de PDF sin salir de su stack de Next.js
Las funciones de Vercel no pueden ejecutar TeX Live, pero sí pueden hacer solicitudes HTTP. La API de FormaTeX convierte una sola llamada fetch en un PDF totalmente compilado.
Despliegue sin configuración
Añada un archivo de ruta de API y una variable de entorno. Haga push a Vercel y su endpoint de PDF estará activo globalmente en segundos.
Compatible con el App Router
El route handler sigue la convención del App Router de Next.js. Exporte runtime, maxDuration y el handler POST; eso es todo.
Respuesta en streaming
Reenvíe los bytes del PDF recibidos directamente al navegador sin almacenar todo el archivo en memoria, para que la invocación de su función sea rápida y económica.
\section{Ruta de API de Next.js}
La ruta de API completa
Cree app/api/pdf/route.ts en su proyecto de Next.js. La ruta acepta un POST con un cuerpo JSON que contiene source y, opcionalmente, engine, y devuelve el PDF compilado al llamador mediante streaming.
// app/api/pdf/route.ts
import type { NextRequest } from "next/server"
// Use the Node.js runtime — the Edge runtime does not support
// the full fetch API response streaming needed for binary files.
export const runtime = "nodejs"
// Vercel Hobby: 10 s max. Pro / Enterprise: up to 300 s.
// Set this to at least 30 s to handle complex documents.
export const maxDuration = 30
export async function POST(request: NextRequest) {
const body = await request.json()
const source: string = body.source ?? ""
const engine: string = body.engine ?? "pdflatex"
if (!source) {
return Response.json({ error: "source is required" }, { status: 400 })
}
const apiKey = process.env.FORMATEX_API_KEY
if (!apiKey) {
return Response.json({ error: "FORMATEX_API_KEY is not configured" }, { status: 500 })
}
const upstream = await fetch("https://api.formatex.io/api/v1/compile", {
method: "POST",
headers: {
"X-API-Key": apiKey,
"Content-Type": "application/json",
},
body: JSON.stringify({ latex: source, engine }),
})
if (!upstream.ok) {
const err = await upstream.json().catch(() => ({ error: "compilation failed" }))
return Response.json(err, { status: upstream.status })
}
// Stream the PDF bytes directly to the client — no buffering in memory.
return new Response(upstream.body, {
headers: {
"Content-Type": "application/pdf",
"Content-Disposition": 'attachment; filename="document.pdf"',
},
})
}\subsection{Cómo llamar a la ruta}
Llame a /api/pdf desde cualquier componente de cliente o server action. La función auxiliar siguiente activa una descarga en el navegador directamente desde el blob.
// Calling the route from a React component or server action
async function generatePdf(latexSource: string): Promise<void> {
const res = await fetch("/api/pdf", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ source: latexSource, engine: "pdflatex" }),
})
if (!res.ok) {
const { error } = await res.json()
throw new Error(error ?? "PDF generation failed")
}
// Trigger a browser download
const blob = await res.blob()
const url = URL.createObjectURL(blob)
const a = document.createElement("a")
a.href = url
a.download = "document.pdf"
a.click()
URL.revokeObjectURL(url)
}\section{Variables de entorno}
Cómo añadir su clave de API a Vercel
Abra los ajustes de su proyecto
Vaya a vercel.com → su proyecto → Settings → Environment Variables.
Añada FORMATEX_API_KEY
Establezca el nombre como FORMATEX_API_KEY y pegue su clave del panel de FormaTeX. Seleccione el entorno Production (y, si lo desea, Preview).
Vuelva a desplegar
Los cambios en las variables de entorno surten efecto en el siguiente despliegue. Inicie un nuevo despliegue desde el panel de Vercel o haciendo push de un nuevo commit.
Nunca exponga FORMATEX_API_KEY al navegador. La variable solo es accesible en el servidor, dentro de un Route Handler o una Server Action, y no se incluye en el bundle del cliente.
\section{Selección del runtime}
Runtime Edge frente a Node.js
Runtime Edge
No recomendado- Límite de CPU de 50 ms: insuficiente para documentos complejos
- Límite de 4 MB en el cuerpo de la respuesta: puede truncar PDF grandes
- Sin módulos integrados de Node.js como Buffer
Runtime de Node.js
Recomendado- Hasta 300 s de ejecución (plan Pro/Enterprise)
- Compatibilidad total con cuerpos de respuesta en streaming
- Buffer y crypto estándar de Node.js disponibles
Establezca export const runtime = "nodejs" al principio del archivo de su ruta. Sin ello, Next.js puede usar por defecto el runtime Edge en Vercel y el streaming del PDF fallará con documentos grandes.
\section{Guías relacionadas}
Más guías para su stack
La API de FormaTeX es un endpoint HTTP sencillo. Acceda a ella desde cualquier lenguaje o plataforma.

