### Start Progress Bar on Visit Start
Source: https://inertiajs.com/docs/v3/advanced/progress-indicators
Use the 'start' event listener to initiate the NProgress bar when a new Inertia visit begins.
```javascript
router.on("start", () => NProgress.start());
```
--------------------------------
### Install React Client-Side Adapter
Source: https://inertiajs.com/docs/v3/getting-started/upgrade-guide
Install the React client-side adapter for Inertia.js v3.
```bash
npm install @inertiajs/react@^3.0
```
--------------------------------
### Build and Start SSR Server in Production
Source: https://inertiajs.com/docs/v3/advanced/server-side-rendering
For production, build both your client and SSR bundles, then start the Node.js SSR server.
```bash
npm run build
php artisan inertia:start-ssr
```
--------------------------------
### Install Svelte Client-Side Adapter
Source: https://inertiajs.com/docs/v3/getting-started/upgrade-guide
Install the Svelte client-side adapter for Inertia.js v3.
```bash
npm install @inertiajs/svelte@^3.0
```
--------------------------------
### Install NProgress Library
Source: https://inertiajs.com/docs/v3/advanced/progress-indicators
Install the NProgress library using npm to manage progress bar functionality.
```bash
npm install nprogress
```
--------------------------------
### Complete Progress Indicator Example (React)
Source: https://inertiajs.com/docs/v3/advanced/progress-indicators
This example shows the full implementation of a custom loading indicator using NProgress with Inertia.js for React.
```js
import NProgress from "nprogress";
import { router } from "@inertiajs/react";
let timeout = null;
router.on("start", () => {
timeout = setTimeout(() => NProgress.start(), 250);
});
router.on("progress", (event) => {
if (NProgress.isStarted() && event.detail.progress.percentage) {
NProgress.set((event.detail.progress.percentage / 100) * 0.9);
}
});
router.on("finish", (event) => {
clearTimeout(timeout);
if (!NProgress.isStarted()) {
return;
}
if (event.detail.visit.completed) {
NProgress.done();
} else if (event.detail.visit.interrupted) {
NProgress.set(0);
} else if (event.detail.visit.cancelled) {
NProgress.done();
NProgress.remove();
}
});
```
--------------------------------
### Complete Progress Indicator Example (Svelte)
Source: https://inertiajs.com/docs/v3/advanced/progress-indicators
This example shows the full implementation of a custom loading indicator using NProgress with Inertia.js for Svelte.
```js
import NProgress from "nprogress";
import { router } from "@inertiajs/svelte";
let timeout = null;
router.on("start", () => {
timeout = setTimeout(() => NProgress.start(), 250);
});
router.on("progress", (event) => {
if (NProgress.isStarted() && event.detail.progress.percentage) {
NProgress.set((event.detail.progress.percentage / 100) * 0.9);
}
});
router.on("finish", (event) => {
clearTimeout(timeout);
if (!NProgress.isStarted()) {
return;
}
if (event.detail.visit.completed) {
NProgress.done();
} else if (event.detail.visit.interrupted) {
NProgress.set(0);
} else if (event.detail.visit.cancelled) {
NProgress.done();
NProgress.remove();
}
});
```
--------------------------------
### Start the Inertia SSR Server
Source: https://inertiajs.com/docs/v3/advanced/server-side-rendering
Use this Artisan command to start the SSR server in production. It defaults to using Node.js as the runtime.
```bash
php artisan inertia:start-ssr
```
--------------------------------
### Install qs dependency
Source: https://inertiajs.com/docs/v3/getting-started/upgrade-guide
Install the 'qs' package directly if your application imports it, as it's no longer a dependency of @inertiajs/core.
```bash
npm install qs
```
--------------------------------
### Complete Progress Indicator Example (Vue)
Source: https://inertiajs.com/docs/v3/advanced/progress-indicators
This example shows the full implementation of a custom loading indicator using NProgress with Inertia.js for Vue.
```js
import NProgress from "nprogress";
import { router } from "@inertiajs/vue3";
let timeout = null;
router.on("start", () => {
timeout = setTimeout(() => NProgress.start(), 250);
});
router.on("progress", (event) => {
if (NProgress.isStarted() && event.detail.progress.percentage) {
NProgress.set((event.detail.progress.percentage / 100) * 0.9);
}
});
router.on("finish", (event) => {
clearTimeout(timeout);
if (!NProgress.isStarted()) {
return;
}
if (event.detail.visit.completed) {
NProgress.done();
} else if (event.detail.visit.interrupted) {
NProgress.set(0);
} else if (event.detail.visit.cancelled) {
NProgress.done();
NProgress.remove();
}
});
```
--------------------------------
### Install Vite Plugin
Source: https://inertiajs.com/docs/v3/getting-started/upgrade-guide
Install the optional Inertia.js Vite plugin for simplified SSR and component resolution.
```bash
npm install @inertiajs/vite@^3.0
```
--------------------------------
### Install Vue 3 Client-Side Adapter
Source: https://inertiajs.com/docs/v3/getting-started/upgrade-guide
Install the Vue 3 client-side adapter for Inertia.js v3.
```bash
npm install @inertiajs/vue3@^3.0
```
--------------------------------
### Install Inertia Laravel Adapter
Source: https://inertiajs.com/docs/v3/installation/server-side-setup
Use Composer to install the official Inertia server-side adapter for Laravel.
```bash
composer require inertiajs/inertia-laravel
```
--------------------------------
### Install React with Vite Plugin
Source: https://inertiajs.com/docs/v3/installation/client-side-setup
Install React, ReactDOM, and the corresponding Vite plugin using npm. This is required for React-based Inertia.js applications.
```bash
npm install react react-dom @vitejs/plugin-react
```
--------------------------------
### Install Vue with Vite Plugin
Source: https://inertiajs.com/docs/v3/installation/client-side-setup
Install Vue and the corresponding Vite plugin using npm. This is a prerequisite for using Vue with Inertia.js.
```bash
npm install vue @vitejs/plugin-vue
```
--------------------------------
### Install Svelte with Vite Plugin
Source: https://inertiajs.com/docs/v3/installation/client-side-setup
Install Svelte and its Vite plugin using npm. This is necessary for Svelte applications using Inertia.js.
```bash
npm install svelte @sveltejs/vite-plugin-svelte
```
--------------------------------
### Install Inertia Vite Plugin
Source: https://inertiajs.com/docs/v3/advanced/server-side-rendering
Install the Inertia Vite plugin to simplify SSR configuration. This plugin automatically detects your SSR entry point.
```bash
npm install @inertiajs/vite
```
--------------------------------
### Install Inertia Client-Side Adapters and Vite Plugin
Source: https://inertiajs.com/docs/v3/installation/client-side-setup
Install the necessary Inertia client-side adapter for your framework (Vue, React, or Svelte) and the Inertia Vite plugin using npm.
```bash
npm install @inertiajs/vue3 @inertiajs/vite
```
```bash
npm install @inertiajs/react @inertiajs/vite
```
```bash
npm install @inertiajs/svelte @inertiajs/vite
```
--------------------------------
### Configure Global Visit Options
Source: https://inertiajs.com/docs/v3/the-basics/manual-visits
Set a visitOptions callback during app initialization to modify options for all requests. This example adds a custom header to all visits.
```js Vue
import { createApp, h } from "vue";
import { createInertiaApp } from "@inertiajs/vue3";
createInertiaApp({
// ...
defaults: {
visitOptions: (href, options) => {
return {
headers: {
...options.headers,
"X-Custom-Header": "value",
},
};
},
},
});
```
```jsx React
import { createInertiaApp } from "@inertiajs/react";
import { createRoot } from "react-dom/client";
createInertiaApp({
// ...
defaults: {
visitOptions: (href, options) => {
return {
headers: {
...options.headers,
"X-Custom-Header": "value",
},
};
},
},
});
```
```js Svelte
import { createInertiaApp } from "@inertiajs/svelte";
createInertiaApp({
// ...
defaults: {
visitOptions: (href, options) => {
return {
headers: {
...options.headers,
"X-Custom-Header": "value",
},
};
},
},
});
```
--------------------------------
### Start Progress Bar with Delay
Source: https://inertiajs.com/docs/v3/advanced/progress-indicators
Modify the 'start' event listener to use `setTimeout` to delay the initiation of the NProgress bar by 250 milliseconds.
```javascript
router.on("start", () => {
timeout = setTimeout(() => NProgress.start(), 250);
});
```
--------------------------------
### Asset Versioning Request/Response Example
Source: https://inertiajs.com/docs/v3/core-concepts/the-protocol
Demonstrates an Inertia request with an asset version and the server's response when versions mismatch, triggering a full-page visit.
```http
REQUEST
GET: https://example.com/events/80
Accept: text/html, application/xhtml+xml
X-Requested-With: XMLHttpRequest
X-Inertia: true
X-Inertia-Version: 6b16b94d7c51cbe5b1fa42aac98241d5
RESPONSE
409: Conflict
X-Inertia-Location: https://example.com/events/80
```
--------------------------------
### Svelte SSR Entry Point
Source: https://inertiajs.com/docs/v3/advanced/server-side-rendering
Set up the SSR entry point for Svelte applications using `@inertiajs/svelte/server`. This example uses Svelte's server-side rendering capabilities.
```javascript
import { createInertiaApp } from '@inertiajs/svelte'
import createServer from '@inertiajs/svelte/server'
import { render } from 'svelte/server'
createServer(page =>
createInertiaApp({
page,
resolve: name => {
const pages = import.meta.glob('./Pages/**/*.svelte')
return pages[`./Pages/${name}.svelte`]()
},
setup({ App, props }) {
return render(App, { props })
},
}),
)
```
--------------------------------
### React SSR Entry Point
Source: https://inertiajs.com/docs/v3/advanced/server-side-rendering
Configure the SSR entry point for React applications using `@inertiajs/react/server`. This setup is for server-side rendering with ReactDOMServer.
```javascript
import { createInertiaApp } from '@inertiajs/react'
import createServer from '@inertiajs/react/server'
import ReactDOMServer from 'react-dom/server'
createServer(page =>
createInertiaApp({
page,
render: ReactDOMServer.renderToString,
resolve: name => {
const pages = import.meta.glob('./Pages/**/*.jsx')
return pages[`./Pages/${name}.jsx`]()
},
setup: ({ App, props }) => ,
}),
)
```
--------------------------------
### Enable Runtime Existence Check
Source: https://inertiajs.com/docs/v3/advanced/server-side-rendering
Configure the `ensure_runtime_exists` option to verify the SSR runtime binary exists before starting the server. The command will error if the binary is not found.
```php
'ssr' => [
'ensure_runtime_exists' => (bool) env('INERTIA_SSR_ENSURE_RUNTIME_EXISTS', false),
],
```
--------------------------------
### React File Upload Example with Inertia Form Helper
Source: https://inertiajs.com/docs/v3/the-basics/file-uploads
Example of a file upload form in React using the Inertia form helper. It includes a text input for 'name' and a file input for 'avatar', with progress tracking.
```jsx
import { useForm } from "@inertiajs/react";
const { data, setData, post, progress } = useForm({
name: null,
avatar: null,
});
function submit(e) {
e.preventDefault();
post("/users");
}
return (
);
```
--------------------------------
### Svelte File Upload Example with Inertia Form Helper
Source: https://inertiajs.com/docs/v3/the-basics/file-uploads
Example of a file upload form in Svelte using the Inertia form helper. It includes a text input for 'name' and a file input for 'avatar', with progress tracking.
```svelte
```
--------------------------------
### Define Layout within
```
--------------------------------
### Install Babel Plugin for Webpack Dynamic Imports
Source: https://inertiajs.com/docs/v3/advanced/code-splitting
Install the `@babel/plugin-syntax-dynamic-import` to enable dynamic imports with Webpack. This is automatically configured if you are using Laravel Mix 6 or above.
```bash
npm install @babel/plugin-syntax-dynamic-import
```
--------------------------------
### Manual Inertia Setup with React
Source: https://inertiajs.com/docs/v3/installation/client-side-setup
Manually configure Inertia.js for React, providing `resolve` and `setup` callbacks. This approach prevents the Vite plugin from auto-generating SSR handling.
```javascript
import { createInertiaApp } from '@inertiajs/react'
import { createRoot } from 'react-dom/client'
createInertiaApp({
resolve: name => {
const pages = import.meta.glob('./Pages/**/*.jsx')
return pages[`./Pages/${name}.jsx`]()
},
setup({ el, App, props }) {
createRoot(el).render()
},
})
```
--------------------------------
### Partial Reload Request/Response Example
Source: https://inertiajs.com/docs/v3/core-concepts/the-protocol
Illustrates a partial reload request for specific props and the server's JSON response containing only the requested data.
```http
REQUEST
GET: https://example.com/events
Accept: text/html, application/xhtml+xml
X-Requested-With: XMLHttpRequest
X-Inertia: true
X-Inertia-Version: 6b16b94d7c51cbe5b1fa42aac98241d5
X-Inertia-Partial-Data: events
X-Inertia-Partial-Component: Events
RESPONSE
HTTP/1.1 200 OK
Content-Type: application/json
{
"component": "Events",
"props": {
"auth": {...}, // NOT included
"categories": [...], // NOT included
"events": [...], // Included
"errors": {} // ALWAYS included
},
"url": "/events/80",
"version": "6b16b94d7c51cbe5b1fa42aac98241d5"
}
```
--------------------------------
### Vue File Upload Example with Inertia Form Helper
Source: https://inertiajs.com/docs/v3/the-basics/file-uploads
Example of a file upload form in Vue using the Inertia form helper. It includes a text input for 'name' and a file input for 'avatar', with progress tracking.
```vue
```
--------------------------------
### Enable Clustering for SSR Server
Source: https://inertiajs.com/docs/v3/advanced/server-side-rendering
Pass `cluster: true` to `createServer` to start multiple Node servers on the same port. Requests will be handled by each thread in a round-robin fashion.
```js
createServer(page =>
createInertiaApp({
// ...
}),
{ cluster: true },
)
```
--------------------------------
### Initial HTML Response Example
Source: https://inertiajs.com/docs/v3/core-concepts/the-protocol
The first request to an Inertia app is a standard HTML request. The server responds with a full HTML document including assets and a JSON payload for the initial page.
```http
REQUEST
GET: https://example.com/events/80
Accept: text/html, application/xhtml+xml
RESPONSE
HTTP/1.1 200 OK
Content-Type: text/html; charset=utf-8
My app
```
--------------------------------
### Loading Data with Buffer
Source: https://inertiajs.com/docs/v3/data-props/load-when-visible
Start loading data a specified number of pixels before the element becomes visible. This helps to pre-fetch data and improve perceived performance.
```vue
{/snippet}
{#each permissions as permission}
{/each}
```
--------------------------------
### Upload Files with Method Spoofing (Svelte)
Source: https://inertiajs.com/docs/v3/the-basics/file-uploads
Use POST with an `_method` attribute to upload files when the server framework supports method spoofing for PUT/PATCH requests. This example uses Svelte.
```javascript
import { router } from "@inertiajs/svelte";
router.post(`/users/${user.id}`, {
_method: "put",
avatar: form.avatar,
});
```
--------------------------------
### Update and Get Inertia.js Configuration at Runtime (React)
Source: https://inertiajs.com/docs/v3/installation/client-side-setup
In React applications, use `config.set()` to update configuration values and `config.get()` to retrieve them at runtime. This is useful for dynamic configuration adjustments.
```javascript
import { config } from "@inertiajs/react";
// Set a single value using dot notation...
config.set("form.recentlySuccessfulDuration", 1000);
config.set("prefetch.cacheFor", "5m");
// Set multiple values at once...
config.set({
"form.recentlySuccessfulDuration": 1000,
"prefetch.cacheFor": "5m",
});
// Get a configuration value...
const duration = config.get("form.recentlySuccessfulDuration");
```
--------------------------------
### Build SSR Bundle with npm
Source: https://inertiajs.com/docs/v3/advanced/server-side-rendering
Use this command to build the SSR bundle when using Laravel Starter Kits with Inertia SSR.
```bash
npm run build:ssr
```
--------------------------------
### Install lodash-es dependency
Source: https://inertiajs.com/docs/v3/getting-started/upgrade-guide
Install the 'lodash-es' package directly if your application imports it, as it's no longer a dependency of @inertiajs/core.
```bash
npm install lodash-es
```
--------------------------------
### Upload Files with Method Spoofing (React)
Source: https://inertiajs.com/docs/v3/the-basics/file-uploads
Use POST with an `_method` attribute to upload files when the server framework supports method spoofing for PUT/PATCH requests. This example uses React.
```javascript
import { router } from "@inertiajs/react";
router.post(`/users/${user.id}`, {
_method: "put",
avatar: form.avatar,
});
```
--------------------------------
### Upload Files with Method Spoofing (Vue)
Source: https://inertiajs.com/docs/v3/the-basics/file-uploads
Use POST with an `_method` attribute to upload files when the server framework supports method spoofing for PUT/PATCH requests. This example uses Vue.
```javascript
import { router } from "@inertiajs/vue3";
router.post(`/users/${user.id}`, {
_method: "put",
avatar: form.avatar,
});
```
--------------------------------
### Use ProvidesInertiaProperties with Inertia::render and with()
Source: https://inertiajs.com/docs/v3/the-basics/responses
Pass an instance of a class implementing `ProvidesInertiaProperties` directly to `Inertia::render` or chain it with the `with()` method to include its properties.
```php
public function index(UserPermissions $permissions)
{
return Inertia::render('UserProfile', $permissions);
// or...
return Inertia::render('UserProfile')->with($permissions);
}
```
--------------------------------
### Setup Root Template (app.blade.php)
Source: https://inertiajs.com/docs/v3/installation/server-side-setup
Create the main Blade template for your Inertia application. This file is loaded on the first page visit and includes necessary Inertia components for head and app rendering. Ensure Vite is configured to build your JavaScript.
```blade
@vite('resources/js/app.js')
```
--------------------------------
### Implement ProvidesInertiaProperty for UserAvatar
Source: https://inertiajs.com/docs/v3/the-basics/responses
Implement the `ProvidesInertiaProperty` interface to transform user data into an avatar URL. The `toInertiaProperty` method receives context and returns the transformed value.
```php
use Inertia\PropertyContext;
use Inertia\ProvidesInertiaProperty;
class UserAvatar implements ProvidesInertiaProperty
{
public function __construct(protected User $user, protected int $size = 64)
{
//
}
public function toInertiaProperty(PropertyContext $context): mixed
{
return $this->user->avatar
? Storage::url($this->user->avatar)
: "https://ui-avatars.com/api/?name={$this->user->name}&size={$this->size}";
}
}
```
--------------------------------
### Check if Progress Bar Started in Progress Event
Source: https://inertiajs.com/docs/v3/advanced/progress-indicators
In the 'progress' event listener, verify that NProgress has started before updating its progress to maintain consistency with the delay logic.
```javascript
router.on("progress", (event) => {
if (!NProgress.isStarted()) {
return;
}
// ...
});
```
--------------------------------
### Initialize Inertia App
Source: https://inertiajs.com/docs/v3/installation/client-side-setup
Update your main JavaScript file to boot your Inertia app. The Vite plugin automatically handles page resolution and mounting, requiring only a minimal entry point.
```javascript
import { createInertiaApp } from '@inertiajs/vue3'
createInertiaApp()
```
```jsx
import { createInertiaApp } from '@inertiajs/react'
createInertiaApp()
```
```javascript
import { createInertiaApp } from '@inertiajs/svelte'
createInertiaApp()
```
--------------------------------
### Enable View Transitions Globally (Svelte)
Source: https://inertiajs.com/docs/v3/the-basics/view-transitions
Configure the `visitOptions` callback when initializing your Inertia app to enable view transitions for all visits.
```javascript
import { createInertiaApp } from "@inertiajs/svelte";
createInertiaApp({
// ...
defaults: {
visitOptions: (href, options) => {
return { viewTransition: true };
},
},
});
```
--------------------------------
### Preserve State with Inertia.js GET requests
Source: https://inertiajs.com/docs/v3/the-basics/manual-visits
Instruct Inertia to preserve the component's state when using the `get` method by setting the `preserveState` option to `true`.
```js Vue
import { router } from "@inertiajs/vue3";
router.get("/users", { search: "John" }, { preserveState: true });
```
```js React
import { router } from "@inertiajs/react";
router.get("/users", { search: "John" }, { preserveState: true });
```
```js Svelte
import { router } from "@inertiajs/svelte";
router.get("/users", { search: "John" }, { preserveState: true });
```
--------------------------------
### Manual Inertia Setup with Svelte
Source: https://inertiajs.com/docs/v3/installation/client-side-setup
Manually configure Inertia.js for Svelte, providing `resolve` and `setup` callbacks. This approach prevents the Vite plugin from auto-generating SSR handling.
```javascript
import { createInertiaApp } from '@inertiajs/svelte'
import { mount } from 'svelte'
createInertiaApp({
resolve: name => {
const pages = import.meta.glob('./Pages/**/*.svelte')
return pages[`./Pages/${name}.svelte`]()
},
setup({ el, App, props }) {
mount(App, { target: el, props })
},
})
```
--------------------------------
### Implement ProvidesInertiaProperties for User Permissions
Source: https://inertiajs.com/docs/v3/the-basics/responses
Implement the `ProvidesInertiaProperties` interface to group related props, such as user permissions. The `toInertiaProperties` method returns an array of key-value pairs.
```php
use App\Models\User;
use Illuminate\Container\Attributes\CurrentUser;
use Inertia\RenderContext;
use Inertia\ProvidesInertiaProperties;
class UserPermissions implements ProvidesInertiaProperties
{
public function __construct(#[CurrentUser] protected User $user)
{
//
}
public function toInertiaProperties(RenderContext $context): array
{
return [
'canEdit' => $this->user->can('edit'),
'canDelete' => $this->user->can('delete'),
'canPublish' => $this->user->can('publish'),
'isAdmin' => $this->user->hasRole('admin'),
];
}
}
```
--------------------------------
### Manual Inertia Setup with Vue
Source: https://inertiajs.com/docs/v3/installation/client-side-setup
Manually configure Inertia.js for Vue, providing `resolve` and `setup` callbacks. This approach prevents the Vite plugin from auto-generating SSR handling.
```javascript
import { createApp, h } from 'vue'
import { createInertiaApp } from '@inertiajs/vue3'
createInertiaApp({
resolve: name => {
const pages = import.meta.glob('./Pages/**/*.vue')
return pages[`./Pages/${name}.vue`]()
},
setup({ el, App, props, plugin }) {
createApp({ render: () => h(App, props) })
.use(plugin)
.mount(el)
},
})
```
--------------------------------
### JavaScript: Programmatic Instant Visit
Source: https://inertiajs.com/docs/v3/the-basics/instant-visits
Initiate an instant visit programmatically using `router.visit()` with the `component` option to specify the target component.
```js
router.visit("/dashboard", {
component: "Dashboard",
});
```
--------------------------------
### Svelte: Making GET requests with useHttp
Source: https://inertiajs.com/docs/v3/the-basics/http-requests
Svelte's `useHttp` hook allows for reactive GET requests. Bind input values and conditionally render a processing indicator.
```svelte
{#if http.processing}
Searching...
{/if}
```
--------------------------------
### Enable Precognition with useForm (Backwards Compatibility)
Source: https://inertiajs.com/docs/v3/the-basics/forms
For backwards compatibility, you can pass the HTTP method and URL as the first arguments to `useForm()`.
```js
const form = useForm("post", "/users", {
name: "",
email: "",
});
```
--------------------------------
### React: Making GET requests with useHttp
Source: https://inertiajs.com/docs/v3/the-basics/http-requests
In React, `useHttp` returns data, methods to update it, and a `get` function for making requests. Manage input changes and display processing state.
```jsx
import { useHttp } from '@inertiajs/react'
export default function Search() {
const { data, setData, get, processing } = useHttp({
query: '',
})
function search(e) {
setData('query', e.target.value)
get('/api/search', {
onSuccess: (response) => {
console.log(response)
},
})
}
return (
<>
{processing &&
Searching...
}
>
)
}
```
--------------------------------
### Check if Progress Bar Started in Finish Event
Source: https://inertiajs.com/docs/v3/advanced/progress-indicators
Add a check within the 'finish' event listener to ensure NProgress has actually started before attempting to finish it, avoiding issues with the delay mechanism.
```javascript
router.on("finish", (event) => {
clearTimeout(timeout);
if (!NProgress.isStarted()) {
return;
}
// ...
});
```
--------------------------------
### Vue: Making GET requests with useHttp
Source: https://inertiajs.com/docs/v3/the-basics/http-requests
Use the `useHttp` hook in Vue to make GET requests. It provides reactive state for query parameters and processing status. onSuccess callback handles the response.
```vue
Searching...
```
--------------------------------
### Vue SSR Entry Point
Source: https://inertiajs.com/docs/v3/advanced/server-side-rendering
Set up the SSR entry point for Vue 3 applications using `@inertiajs/vue3/server`. Ensure all necessary plugins and mixins are included.
```javascript
import { createInertiaApp } from '@inertiajs/vue3'
import createServer from '@inertiajs/vue3/server'
import { createSSRApp, h } from 'vue'
import { renderToString } from 'vue/server-renderer'
createServer(page =>
createInertiaApp({
page,
render: renderToString,
resolve: name => {
const pages = import.meta.glob('./Pages/**/*.vue')
return pages[`./Pages/${name}.vue`]()
},
setup({ App, props, plugin }) {
return createSSRApp({
render: () => h(App, props),
}).use(plugin)
},
}),
)
```
--------------------------------
### Svelte: Basic Instant Visit Link
Source: https://inertiajs.com/docs/v3/the-basics/instant-visits
For Svelte, use the `inertia` action with the `component` option on an anchor tag or the `Link` component for instant visits.
```svelte
import { inertia, Link } from '@inertiajs/svelte'
Dashboard
Dashboard
```
--------------------------------
### Customize Validation Timeout
Source: https://inertiajs.com/docs/v3/the-basics/forms
Adjust the debouncing timeout for validation requests. The default is 1500ms. This example sets it to 500ms.
```vue
```
```jsx
```
```svelte
```
--------------------------------
### Basic Form with useForm in React
Source: https://inertiajs.com/docs/v3/the-basics/forms
Illustrates a login form using the useForm helper in React. It manages form state, handles input changes, and processes form submissions.
```jsx
import { useForm } from "@inertiajs/react";
const { data, setData, post, processing, errors } = useForm({
email: "",
password: "",
remember: false,
});
function submit(e) {
e.preventDefault();
post("/login");
}
return (
);
```
--------------------------------
### Preserve Fragment with Link Component
Source: https://inertiajs.com/docs/v3/the-basics/redirects
When using the Link component, fragments are automatically preserved. This example shows how to link to a section with a fragment.
```vue
import { Link } from '@inertiajs/vue3'
View section
```
```jsx
import { Link } from "@inertiajs/react";
View section
```
```svelte
import { Link } from '@inertiajs/svelte'
View section
```
--------------------------------
### Enable View Transitions Globally (React)
Source: https://inertiajs.com/docs/v3/the-basics/view-transitions
Configure the `visitOptions` callback when initializing your Inertia app to enable view transitions for all visits.
```javascript
import { createInertiaApp } from "@inertiajs/react";
createInertiaApp({
// ...
defaults: {
visitOptions: (href, options) => {
return { viewTransition: true };
},
},
});
```
--------------------------------
### Configure Inertia.js Defaults
Source: https://inertiajs.com/docs/v3/installation/client-side-setup
Pass a `defaults` object to `createInertiaApp()` to set default configurations for features like forms, prefetching, and visit options. The `visitOptions` callback allows for dynamic modification of visit parameters.
```javascript
createInertiaApp({
defaults: {
form: {
recentlySuccessfulDuration: 5000,
},
prefetch: {
cacheFor: "1m",
hoverDelay: 150,
},
visitOptions: (href, options) => {
return {
headers: {
...options.headers,
"X-Custom-Header": "value",
},
};
},
},
// ...
});
```
--------------------------------
### Create First Inertia Response
Source: https://inertiajs.com/docs/v3/installation/server-side-setup
Example of a controller method returning an Inertia response, rendering a specific page component with associated data.
```php
use Inertia\Inertia;
class EventsController extends Controller
{
public function show(Event $event)
{
return Inertia::render('Event/Show', [
'event' => $event->only(
'id',
'title',
'start_date',
'description',
),
]);
}
}
```
--------------------------------
### Add Data as Second Argument to Specific Methods
Source: https://inertiajs.com/docs/v3/the-basics/manual-visits
For convenience, `get()`, `post()`, `put()`, and `patch()` methods accept `data` as their second argument.
```js
import { router } from "@inertiajs/vue3";
router.post("/users", {
name: "John Doe",
email: "john.doe@example.com",
});
```
```js
import { router } from "@inertiajs/react";
router.post("/users", {
name: "John Doe",
email: "john.doe@example.com",
});
```
```js
import { router } from "@inertiajs/svelte";
router.post("/users", {
name: "John Doe",
email: "john.doe@example.com",
});
```
--------------------------------
### Polling with Request Options
Source: https://inertiajs.com/docs/v3/data-props/polling
Pass additional request options, such as `onStart` and `onFinish` callbacks, as the second parameter to the `usePoll` helper.
```vue
import { usePoll } from '@inertiajs/vue3'
usePoll(2000, {
onStart() {
console.log('Polling request started')
},
onFinish() {
console.log('Polling request finished')
},
})
```
```react
import { usePoll } from '@inertiajs/react'
usePoll(2000, {
onStart() {
console.log('Polling request started')
},
onFinish() {
console.log('Polling request finished')
},
})
```
```svelte
import { usePoll } from '@inertiajs/svelte'
usePoll(2000, {
onStart() {
console.log('Polling request started')
},
onFinish() {
console.log('Polling request finished')
},
})
```
--------------------------------
### Manual Polling Control
Source: https://inertiajs.com/docs/v3/data-props/polling
Prevent automatic polling on mount by setting `autoStart: false` and use the returned `start` and `stop` methods for manual control.
```vue
```
```react
import { usePoll } from '@inertiajs/react'
export default () => {
const { start, stop } = usePoll(2000, {}, {
autoStart: false,
})
return (
)
}
```
```svelte
import { usePoll } from '@inertiajs/svelte'
const { start, stop } = usePoll(2000, {}, {
autoStart: false,
})
```
--------------------------------
### router.visit() Method
Source: https://inertiajs.com/docs/v3/the-basics/manual-visits
The `router.visit()` method allows for programmatic navigation and data fetching. It accepts a URL and an options object to customize the visit behavior.
```APIDOC
## router.visit()
### Description
Programmatically makes an Inertia visit to a given URL with customizable options.
### Method
JavaScript Function Call
### Parameters
- **url** (string) - Required - The URL to visit.
- **options** (object) - Optional - Configuration for the visit. Includes:
- **method** (string) - The HTTP method to use (e.g., 'get', 'post'). Defaults to 'get'.
- **data** (object) - Data to send with the request.
- **replace** (boolean) - Whether to replace the current history entry. Defaults to false.
- **preserveState** (boolean) - Whether to preserve the current page state. Defaults to false.
- **preserveScroll** (boolean) - Whether to preserve the current scroll position. Defaults to false.
- **only** (array) - An array of component properties to fetch.
- **except** (array) - An array of component properties to exclude.
- **headers** (object) - Custom HTTP headers to send.
- **errorBag** (string) - The name of the error bag to use.
- **forceFormData** (boolean) - Whether to force the request to use FormData.
- **queryStringArrayFormat** (string) - Format for array query strings (e.g., 'brackets').
- **async** (boolean) - Whether the visit should be asynchronous. Defaults to true.
- **showProgress** (boolean) - Whether to show a progress bar. Defaults to true.
- **fresh** (boolean) - Whether to bypass the cache.
- **reset** (array) - An array of properties to reset.
- **preserveUrl** (boolean) - Whether to preserve the current URL.
- **prefetch** (boolean) - Whether to prefetch the page.
- **preserveErrors** (boolean) - Whether to preserve errors.
- **viewTransition** (boolean) - Whether to use View Transitions API.
- **component** (string) - The name of the component to render.
- **pageProps** (object) - Initial page props.
- **onCancelToken** (function) - Callback for cancel token.
- **onCancel** (function) - Callback when the visit is cancelled.
- **onBefore** (function) - Callback before the visit starts.
- **onStart** (function) - Callback when the visit begins.
- **onProgress** (function) - Callback during the visit progress.
- **onSuccess** (function) - Callback on successful visit.
- **onError** (function) - Callback on visit error.
- **onHttpException** (function) - Callback for HTTP exceptions.
- **onNetworkError** (function) - Callback for network errors.
- **onFinish** (function) - Callback when the visit finishes.
- **onPrefetching** (function) - Callback when prefetching starts.
- **onPrefetched** (function) - Callback when prefetching finishes.
### Request Example
```javascript
router.visit('/users', {
method: 'post',
data: { name: 'John Doe' },
onSuccess: (page) => { console.log('Visit successful!'); }
});
```
### Response
This method does not directly return a value, but triggers navigation and data loading.
```
--------------------------------
### Enable View Transitions Globally (Vue)
Source: https://inertiajs.com/docs/v3/the-basics/view-transitions
Configure the `visitOptions` callback when initializing your Inertia app to enable view transitions for all visits.
```javascript
import { createInertiaApp } from "@inertiajs/vue3";
createInertiaApp({
// ...
defaults: {
visitOptions: (href, options) => {
return { viewTransition: true };
},
},
});
```
--------------------------------
### Conditional Logic with SSR Check (React)
Source: https://inertiajs.com/docs/v3/installation/client-side-setup
Conditionally return elements based on the `ssr` flag. This example wraps the app with a `BrowserProvider` only during client-side rendering.
```jsx
createInertiaApp({
withApp(app, { ssr }) {
if (!ssr) {
return {app}
}
return app
},
})
```
--------------------------------
### Vue: Basic Instant Visit Link
Source: https://inertiajs.com/docs/v3/the-basics/instant-visits
Use the `component` prop on the `Link` component to enable instant visits in Vue. This immediately renders the specified component.
```vue
import { Link } from '@inertiajs/vue3'
Dashboard
```
--------------------------------
### Conditional Logic with SSR Check (Vue)
Source: https://inertiajs.com/docs/v3/installation/client-side-setup
Conditionally apply logic based on the rendering environment. This example adds a browser-only plugin only when not server-side rendering.
```js
createInertiaApp({
withApp(app, { ssr }) {
app.use(i18n)
if (!ssr) {
app.use(browserOnlyPlugin)
}
},
})
```
--------------------------------
### Basic Form with useForm in Vue
Source: https://inertiajs.com/docs/v3/the-basics/forms
Demonstrates a basic login form using the useForm helper in Vue. It binds input values to form data, displays errors, and handles form submission.
```vue
```
--------------------------------
### Accessing Flash Data in Svelte
Source: https://inertiajs.com/docs/v3/data-props/flash-data
Access flash data in Svelte components via the `page` store. This example displays a toast notification if present.
```svelte
{#if page.flash.toast}
{page.flash.toast.message}
{/if}
```
--------------------------------
### HTTP Request and Response for Once Props
Source: https://inertiajs.com/docs/v3/core-concepts/the-protocol
Demonstrates the client request with the 'X-Inertia-Except-Once-Props' header and the server response when a once prop is already loaded on the client. The server skips resolving the 'plans' prop.
```http
REQUEST
GET: https://example.com/billing/upgrade
Accept: text/html, application/xhtml+xml
X-Requested-With: XMLHttpRequest
X-Inertia: true
X-Inertia-Version: 6b16b94d7c51cbe5b1fa42aac98241d5
X-Inertia-Except-Once-Props: plans
RESPONSE
HTTP/1.1 200 OK
Content-Type: application/json
{
"component": "Billing/Upgrade",
"props": {
"errors": {},
"currentPlan": {
"id": 1,
"name": "Basic"
}
},
"url": "/billing/upgrade",
"version": "6b16b94d7c51cbe5b1fa42aac98241d5",
"onceProps": {
"plans": {
"prop": "plans",
"expiresAt": null
}
}
}
```
--------------------------------
### Add @inertiajs/core as a direct dependency
Source: https://inertiajs.com/docs/v3/advanced/typescript
An alternative to hoisting for pnpm users to make @inertiajs/core accessible.
```bash
pnpm add @inertiajs/core
```
--------------------------------
### Accessing Flash Data in React
Source: https://inertiajs.com/docs/v3/data-props/flash-data
Access flash data in React components using `usePage().flash`. This example conditionally renders a toast message.
```jsx
import { usePage } from "@inertiajs/react";
export default function Layout({ children }) {
const { flash } = usePage();
return (
<>
{flash.toast &&
{flash.toast.message}
}
{children}
>
);
}
```
--------------------------------
### Accessing Flash Data in Vue
Source: https://inertiajs.com/docs/v3/data-props/flash-data
Access flash data in Vue components via `usePage().value.flash`. This example shows how to display a toast message.
```vue
{{ page.flash.toast.message }}
```
--------------------------------
### Chaining Flash with back()
Source: https://inertiajs.com/docs/v3/data-props/flash-data
Flash data can be chained directly with the `back()` method for concise redirection after flashing.
```php
return Inertia::flash('newUserId', $user->id)->back();
```
--------------------------------
### Get All Validation Errors
Source: https://inertiajs.com/docs/v3/the-basics/http-requests
Chain `withAllErrors()` to the `useHttp` hook to receive all error messages for a field as an array. This is useful when a field has multiple validation rules.
```js
const http = useHttp({
name: '',
email: '',
}).withAllErrors()
// http.errors.name === ['Name is required.', 'Name must be at least 3 characters.']
```
```js
const http = useHttp({
name: '',
email: '',
}).withAllErrors()
// http.errors.name === ['Name is required.', 'Name must be at least 3 characters.']
```
```js
const http = useHttp({
name: '',
email: '',
}).withAllErrors()
// http.errors.name === ['Name is required.', 'Name must be at least 3 characters.']
```