A Sidecar function to run Inertia server-side rendering on Lambda.

Overview

Sidecar SSR for InertiaJS

🚨 This is currently very much in beta!

You can see a fully working Jetstream + Inertia + Sidecar demo repo at hammerstonedev/sidecar-inertia-demo.

Overview

This package provides a Sidecar function to run Inertia server-side rendering on AWS Lambda.

Sidecar packages, deploys, and executes AWS Lambda functions from your Laravel application.

It works with any Laravel 7 or 8 application, hosted anywhere including your local machine, Vapor, Heroku, a shared virtual server, or any other kind of hosting environment.

Enabling SSR

Following the official Inertia docs on enabling SSR is a good place to start, but there are a few things you can skip:

  • You do not need to npm install @inertiajs/server
  • You do not need to npm install webpack-node-externals
  • Come back here when you get to the "Building your application" section

Make sure that inertia/laravel-inertia is at least version 0.5.1.

Installation

To require this package, run the following:

composer require hammerstone/sidecar-inertia

This will install Sidecar as well.

Using the Sidecar Gateway

Update your AppServiceProvider to use the SidecarGateway as the default Inertia SSR Gateway

namespace App\Providers;

use Hammerstone\Sidecar\Inertia\SidecarGateway;
use Illuminate\Support\ServiceProvider;
use Inertia\Ssr\Gateway;

class AppServiceProvider extends ServiceProvider
{
    public function register()
    {
        // Use Sidecar to run Inertia SSR.
        $this->app->instance(Gateway::class, new SidecarGateway);
    }
}

Updating Configuration

Update your config/inertia.php to include the Sidecar settings

<?php

return [
    'ssr' => [
        'enabled' => true,

        'sidecar' => [
            // The Sidecar function that handles the SSR.
            'handler' => \Hammerstone\Sidecar\Inertia\SSR::class,
            
            // Log some stats on how long each Lambda request takes.
            'timings' => false,
            
            // Throw exceptions, should they occur.
            'debug' => env('APP_DEBUG', false),
            
            // Compile Ziggy routes with the Lambda function.
            'ziggy' => false
        ],
    ],

    // ...
];

Configuring Sidecar

If you haven't already, you'll need to configure Sidecar.

Publish the sidecar.php configuration file by running

php artisan sidecar:install

To configure your Sidecar AWS credentials interactively, you can run

php artisan sidecar:configure

The official Sidecar docs go into much further detail.

Now update your config/sidecar.php to include the function shipped with this package.

<?php

return [
    'functions' => [
        \Hammerstone\Sidecar\Inertia\SSR::class
    ],
    
    // ...
];

Updating Your JavaScript

This only covers Vue3, please follow the Inertia docs for Vue2 or React, and please open any issues.

You'll need to update your webpack.ssr.mix.js file. This should work for most cases, but please open any issues for errors you run into. (This is based on the Inertia docs, with slight modifications.)

const path = require('path')
const mix = require('laravel-mix')

mix
    .js('resources/js/ssr.js', 'public/js')
    .options({
        manifest: false
    })
    .vue({
        version: 3,
        useVueStyleLoader: true,
        options: {
            optimizeSSR: true
        }
    })
    .alias({
        '@': path.resolve('resources/js')
    })
    .webpackConfig({
        target: 'node',
        externals: {
            node: true,
            // Sidecar will ship a file called compiledZiggy as a part of
            // the package. We don't want webpack to try to inline it
            // because it doesn't exist at the time webpack runs.
            // './compiledZiggy': 'require("./compiledZiggy")'
        },
        resolve: {
            alias: {
                // Uncomment if you're using Ziggy.
                // ziggy: path.resolve('vendor/tightenco/ziggy/src/js'),
            },
        },
    })

And update your resources/js/ssr.js to look something like this. The specifics may vary based on your application. If you're using Ziggy, you'll want to uncomment the Ziggy stuff. (This is based on the Inertia docs, with slight modifications.)

import {createSSRApp, h} from 'vue'
import {renderToString} from '@vue/server-renderer'
import {createInertiaApp} from '@inertiajs/inertia-vue3'
// import route from 'ziggy';

exports.handler = async function (event) {
    // This is the file that Sidecar has compiled for us if
    // this application uses Ziggy. We import it using
    // this syntax since it may not exist at all.
    // const compiledZiggy = await import('./compiledZiggy');

    return await createInertiaApp({
        page: event,
        render: renderToString,
        resolve: (name) => require(`./Pages/${name}`),
        setup({app, props, plugin}) {
            // const Ziggy = {
            //     // Start with the stuff that may be baked into this Lambda.
            //     ...(compiledZiggy || {}),
            // 
            //     // Then if they passed anything to us via the event,
            //     // overwrite everything that was baked in.
            //     ...event?.props?.ziggy,
            // }

            // Construct a new location, since window.location is not available.
            // Ziggy.location = new URL(Ziggy.url)

            return createSSRApp({
                render: () => h(app, props),
            }).use(plugin).mixin({
                methods: {
                    // Use our custom Ziggy object as the config.
                    // route: (name, params, absolute, config = Ziggy) => route(name, params, absolute, config),
                },
            })
        },
    });
}

Deploying Your SSR Function

After you have added the SSR function to your sidecar.php, you should run php artisan sidecar:deploy --activate to deploy your function.

This will compile your JavaScript for you as a beforeDeployment hook, so you don't have to worry about remembering to do that first.

Debugging SSR

It's recommended that you deploy your Sidecar function locally so that you can test SSR more quickly. You can run php artisan sidecar:deploy --activate from your local machine and your SSR function will be deployed to Lambda.

You can also set ssr.sidecar.debug to true in your config/inertia.php file, so that Sidecar will throw exceptions when SSR fails instead of falling back to client-side rendering. This will help you diagnose issues quickly.

Ziggy (Optional)

If you are using Ziggy, you'll need to pass some Ziggy information along to your Lambda. You can do that by adding the following to your HandleInertiaRequests middleware.

class HandleInertiaRequests extends Middleware
{
    public function share(Request $request)
    {
        $ziggy = new Ziggy($group = null, $request->url());
        $ziggy = $ziggy->toArray();

        // During development, send over the entire Ziggy object, so that
        // when routes change we don't have to redeploy.  In production,
        // only send the current URL, as we will bake the Ziggy config
        // into the Lambda SSR package.
        $ziggy = app()->environment('production') ? Arr::only($ziggy, 'url') : $ziggy;

        return array_merge(parent::share($request), [
            'ziggy' => $ziggy
        ]);
    }
}
You might also like...
An open source blog, made using Laravel, Inertia.js, and React.js. Also a learning repository.

Blog An open source Laravel-based blog. Still in progress, will be updated regularly as I wrote articles on my blog. Configurations Shared-hosting, an

Data providers encapsulate logic for Inertia views, keep your controllers clean and simple.

Laravel Data Providers for Inertia.js Data providers encapsulate logic for Inertia views, keep your controllers clean and simple. Installation We assu

Starter - Laravel, Vue, Inertia, Tailwind, Vite

Starter - Laravel, Vue, Inertia, Tailwind, Vite Laravel-vite preset Laravel 9 Vue 3 Inertia Tailwind Vite Including Sail (Docker). php 8.1 mysql 8.0 p

laravel5.5和vue.js结合的前后端分离项目模板,后端使用了laravel的LTS版本(5.5),前端使用了流行的vue-element-template项目。作为程序的起点,可以直接以此为基础来进行业务扩展。模板内容包括基础的用户管理和权限管理、日志管理、集成第三方登录,整合laravel-echo-server 实现了websocket 做到了消息的实时推送,并在此基础上,实现了聊天室和客服功能。权限管理包括后端Token认证和前端vue.js的动态权限,解决了前后端完整分离的情况下,vue.js的认证与权限相关的痛点,已在本人的多个项目中集成使用。 FacEssential is a Core for PMMP, it gathers all kind of plugins needed to create a faction server. It was created from scratch by Clouds#0667.
FacEssential is a Core for PMMP, it gathers all kind of plugins needed to create a faction server. It was created from scratch by Clouds#0667.

FacEssential FacEssential is a Core for PMMP, it gathers all kind of plugins needed to create a faction server. It was created from scratch by Clouds#

Cipi is a Laravel based cloud server control panel that supports Digital Ocean, AWS, Vultr, Google Cloud, Linode, Azure and other VPS.
Cipi is a Laravel based cloud server control panel that supports Digital Ocean, AWS, Vultr, Google Cloud, Linode, Azure and other VPS.

Cipi is a Laravel based cloud server control panel that supports Digital Ocean, AWS, Vultr, Google Cloud, Linode, Azure and other VPS. It comes with nginx, Mysql, multi PHP-FPM versions, multi users, Supervisor, Composer, npm, free Let's Encrypt certificates, Git deployment, backups, ffmpeg, fail2ban, Redis, API and with a simple graphical interface useful to manage Laravel, Codeigniter, Symfony, WordPress or other PHP applications. With Cipi you don’t need to be a Sys Admin to deploy and manage websites and PHP applications powered by cloud VPS.

Pterodactyl is an open-source game server management panel built with PHP 7, React, and Go
Pterodactyl is an open-source game server management panel built with PHP 7, React, and Go

Pterodactyl Panel Pterodactyl is an open-source game server management panel built with PHP 7, React, and Go. Designed with security in mind, Pterodac

Run Browsershot on AWS Lambda with Sidecar for Laravel

Run Browsershot on AWS Lambda with Sidecar for Laravel This package allows you to run Browsershot on AWS Lambda through Sidecar. You won't need to ins

λ Run PHP Coroutines & Fibers as-a-Service on the AWS Lambda.
λ Run PHP Coroutines & Fibers as-a-Service on the AWS Lambda.

λ Swoole Runtime for AWS Lambda Run PHP Coroutines & Fibers as-a-Service on the AWS Lambda. Getting started Create your Lambda function index.php ?ph

Making multiple identical function calls has the same effect as making a single function call.

Making multiple identical function calls has the same effect as making a single function call.

Builds PHP so that multiple versions can be used side by side.

php-build php-build is a utility for building versions of PHP to use them side by side with each other. The overall structure is loosly borrowed from

A comprehensive library for generating differences between two strings in multiple formats (unified, side by side HTML etc). Based on the difflib implementation in Python

PHP Diff Class Introduction A comprehensive library for generating differences between two hashable objects (strings or arrays). Generated differences

To run time/IO related unit tests (e.g., sleep function calls, database queries, API calls, etc) faster using Swoole.

To run time/IO related unit tests (e.g., sleep function calls, database queries, API calls, etc) faster using Swoole.

Monorepo of the PoP project, including: a server-side component model in PHP, a GraphQL server, a GraphQL API plugin for WordPress, and a website builder
Monorepo of the PoP project, including: a server-side component model in PHP, a GraphQL server, a GraphQL API plugin for WordPress, and a website builder

PoP PoP is a monorepo containing several projects. The GraphQL API for WordPress plugin GraphQL API for WordPress is a forward-looking and powerful Gr

Monorepo of the PoP project, including: a server-side component model in PHP, a GraphQL server, a GraphQL API plugin for WordPress, and a website builder
Monorepo of the PoP project, including: a server-side component model in PHP, a GraphQL server, a GraphQL API plugin for WordPress, and a website builder

PoP PoP is a monorepo containing several projects. The GraphQL API for WordPress plugin GraphQL API for WordPress is a forward-looking and powerful Gr

Run your WP site on github pages, php innovation award winner  https://www.phpclasses.org/package/12091-PHP-Make-a-WordPress-site-run-on-GitHub-pages.html
Run your WP site on github pages, php innovation award winner https://www.phpclasses.org/package/12091-PHP-Make-a-WordPress-site-run-on-GitHub-pages.html

Gitpress Run wordpress directly on github pages Gitpress won the innovation award for may 2021 Read more about this https://naveen17797.github.io/gitp

This project processes a small database with php all on a web server. This project uses XAMPP to run the web server and the database.

PHP-introduction This project processes a small database with php all on a web server. This project uses XAMPP to run the web server and the database.

Lambda calculus interpreter in PHP.
Lambda calculus interpreter in PHP.

lambda-php Lambda calculus interpreter in PHP. Lambda calculus Lambda calculus is a very minimal programming language that was invented in 1936 by Alo

Deploy and execute non-PHP AWS Lambda functions from your Laravel application.

Sidecar for Laravel Deploy and execute non-PHP AWS Lambda functions from your Laravel application. Read the full docs at hammerstone.dev/sidecar/docs.

Comments
  • Support for Laravel 9.x

    Support for Laravel 9.x

    I think we could get away with just using the config() function as this is meant to be used with Laravel anyway... and require testbench for dev and testing.

    opened by felixdorn 3
  • Error: Cannot find module 'ssr' Require stack: - /var/runtime/UserFunction.js

    Error: Cannot find module 'ssr' Require stack: - /var/runtime/UserFunction.js

    Hello,

    I try to use inertia SSR with sidecar and when i want to show any page i have :

    Lambda Execution Exception for Hammerstone\Sidecar\Inertia\SSR: "Error: Cannot find module 'ssr' Require stack: - /var/runtime/UserFunction.js - /var/runtime/Runtime.js - /var/runtime/index.js. [TRACE] Runtime.ImportModuleError: Error: Cannot find module 'ssr' Require stack: - /var/runtime/UserFunction.js".

    I read all instructions and now i don't understand this error and what is missing ?

    It's my error https://flareapp.io/share/Lm83LRp5#F12

    Lucas.

    opened by luluxe 2
  • Update Sidecar and Inertia requirements

    Update Sidecar and Inertia requirements

    Currently the Sidecar version is locked at v0.3.9, while the latest version is v0.3.12, this updates the requirement to ^0.3.9 The inertiajs/inertia-laravel requirement is also updated to allow for versions 0.6.x as it currently only allows ^0.5.1

    opened by RobertBoes 1
  • Add support for Vite

    Add support for Vite

    The way Vite handles SSR is a good bit different than Webpack, so I created a new Sidecar function ViteSSR and split up the install instructions where I thought made sense. Another option I thought of is having the package check for existence of a vite.config.js file to auto-determine which Sidecar function to use.

    The biggest difference is that Vite externalizes dependencies by default, so we need to include node_modules in the Sidecar package. Of course that means we need to worry about the size of node_modules as to not hit the Lambda size limit.

    Feel free to do whatever with this- hope it's able to help someone out!

    opened by prestonholt 7
Releases(v0.0.4)
  • v0.0.4(Mar 31, 2022)

    What's Changed

    • Support for Laravel 9.x by @felixdorn in https://github.com/hammerstonedev/sidecar-inertia/pull/2

    New Contributors

    • @felixdorn made their first contribution in https://github.com/hammerstonedev/sidecar-inertia/pull/2

    Full Changelog: https://github.com/hammerstonedev/sidecar-inertia/compare/v0.0.3...v0.0.4

    Source code(tar.gz)
    Source code(zip)
  • v0.0.3(Jan 9, 2022)

    v0.0.3 - January 9th, 2022

    Added

    • Added the ability to compile Ziggy into the function itself if requested.

    Full Changelog: https://github.com/hammerstonedev/sidecar-inertia/compare/v0.0.2...v0.0.3

    Source code(tar.gz)
    Source code(zip)
  • v0.0.2(Jan 9, 2022)

    What's Changed

    • fix: syntax error, arguments in wrong order by @deanmcpherson in https://github.com/hammerstonedev/sidecar-inertia/pull/1

    New Contributors

    • @deanmcpherson made their first contribution in https://github.com/hammerstonedev/sidecar-inertia/pull/1

    Full Changelog: https://github.com/hammerstonedev/sidecar-inertia/compare/v0.0.1...v0.0.2

    Source code(tar.gz)
    Source code(zip)
  • v0.0.1(Jan 8, 2022)

Owner
Hammerstone
Making tools to make your life easier.
Hammerstone
Starterkits Project With Laravel + Inertia JS + Vue + Vuetify

Laravel InertiaJS Vuetify A laravel inertiajs vuetify starterkit Demo You can access demo app in : https://laravel-inertia-vuetify.herokuapp.com/ Feat

Ahmad Faiz Kamaludin 21 Dec 16, 2022
Laravel backend Inertia and Vue starter template

Inertia.js - Vue.js ve Laravel Starter Template Yunus Emre Altanay If you want to make a single page application using laravel infrastructure. This re

Yunus Emre Altanay 3 Oct 21, 2021
Clone do instagram utilizando Laravel, Vue, Inertia, Tailwind

About Laravel Laravel is a web application framework with expressive, elegant syntax. We believe development must be an enjoyable and creative experie

Bortolin Furlanetto 1 Jan 3, 2022
Laravel Starter With Laravel, Vite, Vue 2, Inertia.js, Ziggy

About Laravel Laravel is a web application framework with expressive, elegant syntax. We believe development must be an enjoyable and creative experie

Oskars Germovs 1 Oct 29, 2021
Laravel Starter With Laravel, Vite, Vue 2, Inertia.js, Ziggy, Typescript

About Laravel Laravel is a web application framework with expressive, elegant syntax. We believe development must be an enjoyable and creative experie

Oskars Germovs 1 Oct 29, 2021
A starter kit that integrates Laravel with Vue CLI, Inertia.js, TailwindCSS and Vuetify

Laravel Viltify Laravel Viltify is a heavily opinionated Laravel starter kit. It's intent is to seamlessly integrate V ue, I nertia.js, L aravel, T ai

Matheus Dal'Pizzol 50 Jan 4, 2023
A template for web development using Laravel, Inertia and Svelte

About Laravel Laravel is a web application framework with expressive, elegant syntax. We believe development must be an enjoyable and creative experie

Atikur Rahman Chitholian 0 Dec 26, 2021
It's a dashboard theme/UI-Starter Kit with Laravel, Inertia and Vue (JetStream).

TailAdmin Inertia It's a dashboard theme/UI-Starter Kit with Laravel, Inertia and Vue (JetStream). Setup Directions npm install composer install Chang

Sinan AYDOĞAN 121 Dec 31, 2022
Building Student Management CRUD with LARAVEL VUE and INERTIA

Building Student Management CRUD with LARAVEL VUE and INERTIA. the amazing thing about I got by combining these technologies is we ca build single page application or SPA .

Tauseed 3 Apr 4, 2022
Laravel Starter Kit (Inertia-SSR - Vue3 - Bootstrap 5)

Laravel Starter Kit (Inertia-SSR - Vue3 - Bootstrap 5) Use this starter kit to develop with Laravel 9 setup InertiaJs with Server Side Rendering (SSR)

Sourav Kumar Tah 16 Nov 16, 2022