Skip to content

Fixing Inertia SSR errors #74

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 8 commits into from
Mar 6, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 23 additions & 0 deletions app/Http/Middleware/HandleAppearance.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\View;
use Symfony\Component\HttpFoundation\Response;

class HandleAppearance
{
/**
* Handle an incoming request.
*
* @param \Closure(\Illuminate\Http\Request): (\Symfony\Component\HttpFoundation\Response) $next
*/
public function handle(Request $request, Closure $next): Response
{
View::share('appearance', $request->cookie('appearance') ?? 'system');

return $next($request);
}
}
5 changes: 5 additions & 0 deletions app/Http/Middleware/HandleInertiaRequests.php
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
use Illuminate\Foundation\Inspiring;
use Illuminate\Http\Request;
use Inertia\Middleware;
use Tighten\Ziggy\Ziggy;

class HandleInertiaRequests extends Middleware
{
Expand Down Expand Up @@ -45,6 +46,10 @@ public function share(Request $request): array
'auth' => [
'user' => $request->user(),
],
'ziggy' => [
...(new Ziggy)->toArray(),
'location' => $request->url(),
],
];
}
}
4 changes: 4 additions & 0 deletions bootstrap/app.php
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
<?php

use App\Http\Middleware\HandleAppearance;
use App\Http\Middleware\HandleInertiaRequests;
use Illuminate\Foundation\Application;
use Illuminate\Foundation\Configuration\Exceptions;
Expand All @@ -13,7 +14,10 @@
health: '/up',
)
->withMiddleware(function (Middleware $middleware) {
$middleware->encryptCookies(except: ['appearance']);

$middleware->web(append: [
HandleAppearance::class,
HandleInertiaRequests::class,
AddLinkHeadersForPreloadedAssets::class,
]);
Expand Down
5 changes: 5 additions & 0 deletions composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,11 @@
"dev": [
"Composer\\Config::disableProcessTimeout",
"npx concurrently -c \"#93c5fd,#c4b5fd,#fb7185,#fdba74\" \"php artisan serve\" \"php artisan queue:listen --tries=1\" \"php artisan pail --timeout=0\" \"npm run dev\" --names=server,queue,logs,vite"
],
"dev:ssr": [
"npm run build:ssr",
"Composer\\Config::disableProcessTimeout",
"npx concurrently -c \"#93c5fd,#c4b5fd,#fb7185,#fdba74\" \"php artisan serve\" \"php artisan queue:listen --tries=1\" \"php artisan pail --timeout=0\" \"php artisan inertia:start-ssr\" --names=server,queue,logs,ssr"
]
},
"extra": {
Expand Down
2 changes: 1 addition & 1 deletion resources/js/components/TextLink.vue
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ defineProps<Props>();
:tabindex="tabindex"
:method="method"
:as="as"
class="hover:!decoration-current text-foreground underline decoration-neutral-300 underline-offset-4 transition-colors duration-300 ease-out dark:decoration-neutral-500"
class="text-foreground underline decoration-neutral-300 underline-offset-4 transition-colors duration-300 ease-out hover:!decoration-current dark:decoration-neutral-500"
>
<slot />
</Link>
Expand Down
51 changes: 46 additions & 5 deletions resources/js/composables/useAppearance.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,28 +3,63 @@ import { onMounted, ref } from 'vue';
type Appearance = 'light' | 'dark' | 'system';

export function updateTheme(value: Appearance) {
if (typeof window === 'undefined') {
return;
}

if (value === 'system') {
const systemTheme = window.matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light';
const mediaQueryList = window.matchMedia('(prefers-color-scheme: dark)');
const systemTheme = mediaQueryList.matches ? 'dark' : 'light';

document.documentElement.classList.toggle('dark', systemTheme === 'dark');
} else {
document.documentElement.classList.toggle('dark', value === 'dark');
}
}

const mediaQuery = window.matchMedia('(prefers-color-scheme: dark)');
const setCookie = (name: string, value: string, days = 365) => {
if (typeof document === 'undefined') {
return;
}

const maxAge = days * 24 * 60 * 60;

document.cookie = `${name}=${value};path=/;max-age=${maxAge};SameSite=Lax`;
};

const mediaQuery = () => {
if (typeof window === 'undefined') {
return null;
}

return window.matchMedia('(prefers-color-scheme: dark)');
};

const getStoredAppearance = () => {
if (typeof window === 'undefined') {
return null;
}

return localStorage.getItem('appearance') as Appearance | null;
};

const handleSystemThemeChange = () => {
const currentAppearance = localStorage.getItem('appearance') as Appearance | null;
const currentAppearance = getStoredAppearance();

updateTheme(currentAppearance || 'system');
};

export function initializeTheme() {
if (typeof window === 'undefined') {
return;
}

// Initialize theme from saved preference or default to system...
const savedAppearance = localStorage.getItem('appearance') as Appearance | null;
const savedAppearance = getStoredAppearance();
updateTheme(savedAppearance || 'system');

// Set up system theme change listener...
mediaQuery.addEventListener('change', handleSystemThemeChange);
mediaQuery()?.addEventListener('change', handleSystemThemeChange);
}

export function useAppearance() {
Expand All @@ -42,7 +77,13 @@ export function useAppearance() {

function updateAppearance(value: Appearance) {
appearance.value = value;

// Store in localStorage for client-side persistence...
localStorage.setItem('appearance', value);

// Store in cookie for SSR...
setCookie('appearance', value);

updateTheme(value);
}

Expand Down
6 changes: 4 additions & 2 deletions resources/js/layouts/settings/Layout.vue
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import Heading from '@/components/Heading.vue';
import { Button } from '@/components/ui/button';
import { Separator } from '@/components/ui/separator';
import { type NavItem } from '@/types';
import { Link } from '@inertiajs/vue3';
import { Link, usePage } from '@inertiajs/vue3';

const sidebarNavItems: NavItem[] = [
{
Expand All @@ -20,7 +20,9 @@ const sidebarNavItems: NavItem[] = [
},
];

const currentPath = window.location.pathname;
const page = usePage();

const currentPath = page.props.ziggy?.location ? new URL(page.props.ziggy.location).pathname : '';
</script>

<template>
Expand Down
2 changes: 1 addition & 1 deletion resources/js/pages/settings/Profile.vue
Original file line number Diff line number Diff line change
Expand Up @@ -77,7 +77,7 @@ const submit = () => {
:href="route('verification.send')"
method="post"
as="button"
class="hover:!decoration-current text-foreground underline decoration-neutral-300 underline-offset-4 transition-colors duration-300 ease-out dark:decoration-neutral-500"
class="text-foreground underline decoration-neutral-300 underline-offset-4 transition-colors duration-300 ease-out hover:!decoration-current dark:decoration-neutral-500"
>
Click here to resend the verification email.
</Link>
Expand Down
41 changes: 41 additions & 0 deletions resources/js/ssr.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
import { createInertiaApp } from '@inertiajs/vue3';
import createServer from '@inertiajs/vue3/server';
import { renderToString } from '@vue/server-renderer';
import { resolvePageComponent } from 'laravel-vite-plugin/inertia-helpers';
import { createSSRApp, h } from 'vue';
import { route as ziggyRoute } from 'ziggy-js';

const appName = import.meta.env.VITE_APP_NAME || 'Laravel';

createServer((page) =>
createInertiaApp({
page,
render: renderToString,
title: (title) => `${title} - ${appName}`,
resolve: (name) => resolvePageComponent(`./pages/${name}.vue`, import.meta.glob('./pages/**/*.vue')),
setup({ App, props, plugin }) {
const app = createSSRApp({ render: () => h(App, props) });

// Configure Ziggy for SSR...
const ziggyConfig = {
...page.props.ziggy,
location: new URL(page.props.ziggy.location),
};

// Create route function...
const route = (name: string, params?: any, absolute?: boolean) => ziggyRoute(name, params, absolute, ziggyConfig);

// Make route function available globally...
app.config.globalProperties.route = route;

// Make route function available globally for SSR...
if (typeof window === 'undefined') {
global.route = route;
}

app.use(plugin);

return app;
},
}),
);
5 changes: 5 additions & 0 deletions resources/js/types/globals.d.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
import type { route as routeFn } from 'ziggy-js';

declare global {
const route: typeof routeFn;
}
2 changes: 2 additions & 0 deletions resources/js/types/index.ts → resources/js/types/index.d.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import type { PageProps } from '@inertiajs/core';
import type { LucideIcon } from 'lucide-vue-next';
import type { Config } from 'ziggy-js';

export interface Auth {
user: User;
Expand All @@ -21,6 +22,7 @@ export interface SharedData extends PageProps {
name: string;
quote: { message: string; author: string };
auth: Auth;
ziggy: Config & { location: string };
}

export interface User {
Expand Down
File renamed without changes.
28 changes: 27 additions & 1 deletion resources/views/app.blade.php
Original file line number Diff line number Diff line change
@@ -1,9 +1,35 @@
<!DOCTYPE html>
<html lang="{{ str_replace('_', '-', app()->getLocale()) }}">
<html lang="{{ str_replace('_', '-', app()->getLocale()) }}" @class(['dark' => ($appearance ?? 'system') == 'dark'])>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">

{{-- Inline script to detect system dark mode preference and apply it immediately --}}
<script>
(function() {
const appearance = '{{ $appearance ?? "system" }}';

if (appearance === 'system') {
const prefersDark = window.matchMedia('(prefers-color-scheme: dark)').matches;

if (prefersDark) {
document.documentElement.classList.add('dark');
}
}
})();
</script>

{{-- Inline style to set the HTML background color based on our theme in app.css --}}
<style>
html {
background-color: oklch(1 0 0);
}

html.dark {
background-color: oklch(0.145 0 0);
}
</style>

<title inertia>{{ config('app.name', 'Laravel') }}</title>

<link rel="preconnect" href="https://fonts.bunny.net">
Expand Down
7 changes: 6 additions & 1 deletion tsconfig.json
Original file line number Diff line number Diff line change
Expand Up @@ -119,5 +119,10 @@
// "skipDefaultLibCheck": true, /* Skip type checking .d.ts files that are included with TypeScript. */
"skipLibCheck": true /* Skip type checking all .d.ts files. */
},
"include": ["resources/js/**/*.ts", "resources/js/**/*.d.ts", "resources/js/**/*.tsx", "resources/js/**/*.vue"]
"include": [
"resources/js/**/*.ts",
"resources/js/**/*.d.ts",
"resources/js/**/*.tsx",
"resources/js/**/*.vue"
]
}
3 changes: 3 additions & 0 deletions vite.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,12 +3,14 @@ import autoprefixer from 'autoprefixer';
import laravel from 'laravel-vite-plugin';
import path from 'path';
import tailwindcss from 'tailwindcss';
import { resolve } from 'node:path';
import { defineConfig } from 'vite';

export default defineConfig({
plugins: [
laravel({
input: ['resources/js/app.ts'],
ssr: 'resources/js/ssr.ts',
refresh: true,
}),
vue({
Expand All @@ -23,6 +25,7 @@ export default defineConfig({
resolve: {
alias: {
'@': path.resolve(__dirname, './resources/js'),
'ziggy-js': resolve(__dirname, 'vendor/tightenco/ziggy'),
},
},
css: {
Expand Down