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

SvelteKit服务端加载数据在Chrome Sources/index暴露问题求助

解决SvelteKit服务端数据暴露在浏览器Sources中的问题

问题原因

这不是Bug,是SvelteKit SSR(服务端渲染)的正常特性:服务端load函数返回的数据会被序列化并嵌入到页面的__data__脚本中,用于客户端的水合过程,所以浏览器能在Sources面板中看到这些数据。你的情况是因为返回的topic或user对象包含了敏感信息,导致这些内容被传到了客户端。

解决方案

1. 过滤敏感字段,只返回前端必需的数据

修改+page.server.js中的getTopic函数,从查询源头和返回结果两层过滤敏感信息:

export const load = ({ locals, setHeaders }) => {
    setHeaders({
        'Cache-Control': `max-age=0, s-maxage=60`,
    })
    const getTopic = async () => {
        try {
            // 调用PocketBase时指定需要的字段,从源头减少冗余数据
            const topic = serializeNonPOJOs(
                await locals.pb.collection("topic").getFullList(undefined,{
                    sort: '-created',
                    // 仅请求页面需要的字段,排除敏感信息
                    fields: 'id,title,content,author.username,author.avatar'
                }),
            );
            // 二次过滤,确保没有漏网的敏感数据
            return topic.map(item => ({
                id: item.id,
                title: item.title,
                content: item.content,
                author: {
                    username: item.author.username,
                    avatar: item.author.avatar
                }
            }));
        } catch (err) {
            console.log("Error:", err);
            throw error(err.status, err.message);
        }
    };
    return {
        topic: getTopic(),
    };
};

2. 限制服务端locals.user的敏感数据

在handle钩子中,不要把完整的用户模型赋值给event.locals.user,只保留非敏感字段:

try {
    if (event.locals.pb.authStore.isValid) {
        await event.locals.pb.collection('users').authRefresh();
        const model = serializeNonPOJOs(event.locals.pb.authStore.model);
        // 仅保留服务端逻辑需要的非敏感字段
        event.locals.user = {
            id: model.id,
            username: model.username,
            avatar: model.avatar
            // 移除email、phone等敏感字段
        };
    }
} catch (_) {
    event.locals.pb.authStore.clear();
    event.locals.user = undefined;
}

3. 敏感数据仅在服务端处理

如果需要用到敏感信息的逻辑(比如权限校验、数据筛选),全部放在服务端完成,绝不传递到前端:

  • 在+page.server.js的load函数中,用locals.user.id做权限判断,而非把邮箱等敏感信息传到前端处理。
  • 如需操作用户敏感数据,创建专门的+server.js路由,在服务端完成操作后,前端只接收处理结果。

额外提醒

  • 即使通过PocketBase权限规则限制了前端直接访问敏感数据,服务端查询时如果不指定fields参数,仍然会返回完整的用户对象,必须在服务端主动过滤。
  • 检查所有路由和组件,确保没有其他地方不小心将敏感数据传递到客户端。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.25 07:28:10