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

如何在Ruby on Rails中结合Inertia.js 1.0实现SSR?

Svelte + Inertia.js + Rails SSR 部署失败排查与修复指南

核心配置校验

  • 确认Rails端SSR依赖:检查Gemfile中是否包含inertia-rails和inertia_ssr,执行bundle install后,在config/application.rb中添加require "inertia_ssr"。
  • 验证Node.js环境:确保项目根目录的package.json已安装@inertiajs/svelte-server、@inertiajs/server依赖,执行npm install或yarn install完成依赖安装。

Rails端SSR配置检查

  • 核对config/initializers/inertia.rb的SSR设置:
    Inertia.configure do |config|
      config.ssr_enabled = true
      config.ssr_url = "http://localhost:13714" # 确保与Node服务端口一致
    end
    
  • 启动Node SSR服务:执行项目根目录的bin/inertia-ssr脚本,或直接运行node ./ssr/index.js(根据你的SSR入口路径调整),确认服务无报错且正常监听指定端口。

Svelte组件适配SSR要求

  • 规避浏览器专属API:页面组件中若需使用window、document等浏览器API,需放在onMount钩子中调用,或通过条件判断区分SSR与客户端环境:
    <script>
      import { onMount } from 'svelte'
    
      let clientOnlyData = null
    
      onMount(() => {
        clientOnlyData = window.someBrowserProperty
      })
    </script>
    
    {#if clientOnlyData}
      <span>{clientOnlyData}</span>
    {/if}
    
  • 组件导出规范:确保页面组件为默认导出,且正确接收props参数,无语法错误。

路由与渲染验证

  • 为目标页面启用SSR:在Rails控制器中明确指定ssr: true:
    def detail
      render inertia: 'Pages/Detail', props: { item: @item }, ssr: true
    end
    
  • 验证SSR生效:访问页面后查看源码,若能看到组件渲染后的HTML内容(而非空挂载容器),说明SSR正常;若为空容器,检查Node服务日志是否有报错、Rails日志是否存在SSR请求记录。

常见问题排查

  • Node服务启动失败:检查ssr/index.js入口文件是否正确导入渲染器与路由配置,示例:
    import { createServer } from '@inertiajs/server'
    import { createSvelteRenderer } from '@inertiajs/svelte-server'
    
    createServer(createSvelteRenderer(page => import(`./pages/${page.component}.svelte`)), {
      // 自定义配置
    })
    
  • 端口/网络问题:确保Rails与Node服务在同一网络环境,端口未被占用,防火墙未拦截请求。
  • 版本冲突:核对inertia-rails、@inertiajs/svelte、@inertiajs/svelte-server的版本兼容性,优先使用模板对应的版本号。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.16 03:02:13