You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Vercel部署SvelteKit SSR应用遇FUNCTION_INVOCATION_TIMEOUT超时错误

Vercel部署SSR SvelteKit应用时遭遇FUNCTION_INVOCATION_TIMEOUT(504网关超时)错误

我在Vercel免费版上部署带有服务端渲染(SSR)的SvelteKit应用时,触发了FUNCTION_INVOCATION_TIMEOUT错误,部署失败并返回504: GATEWAY_TIMEOUT,提示无服务器函数在10秒后超时。

我的应用包含一个无服务器函数,用于从MongoDB数据库获取数据并在客户端渲染。我已经对该函数做了优化:

  • 复用MongoDB连接
  • 添加异常捕获的错误处理

但即便如此,部署仍因超时错误失败。

注意:

  • 使用客户端渲染(CSR)时部署可成功
  • 环境为Vercel免费版

无服务器函数代码(+server.ts):

import { Collection, MongoClient, type Document } from "mongodb";
import { json } from "@sveltejs/kit";

let cachedDb: { client: MongoClient; blogCollection: Collection<Document>; } | null = null;

async function connectToDatabase() {
  if (cachedDb) {
    return cachedDb;
  }

  const client = new MongoClient(DB_URI);
  await client.connect();
  const db = client.db("blogs");
  const blogCollection = db.collection("blogs");

  cachedDb = { client, blogCollection };
  return cachedDb;
}

export async function GET() {
  try {
    const { blogCollection } = await connectToDatabase();
    const result = await blogCollection.find().toArray();
    return json(result, { status: 201 });
  } catch (error) {
    console.error("GET request error:", error);
    return json({ error: "Internal Server Error" }, { status: 500 });
  }
}

SSR页面代码(+page.ts):

export type PageServerLoad = (props: {
  fetch: typeof fetch;
}) => Promise<{ [key: string]: any }>;

let blogs = [];

export const load: PageServerLoad = async ({ fetch }) => {
  const response = await fetch("/api/blogs");
  blogs = await response.json();

  return {
    blogs,
  };
};

错误页面截图:

错误页面截图

内容的提问来源于stack exchange,提问作者FD3

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.29 09:07:39