Powerful routing helper for Inertia.js v2 applications
Work seamlessly with Laravel Ziggy or Wayfinder routes, with full support for subfolder deployments, query parameters, and route validation.
Features âĒ Installation âĒ Usage âĒ API Reference âĒ Examples
/init import for setup, main import for usagenpm install @tunbudi06/inertia-route-helper
yarn add @tunbudi06/inertia-route-helper
pnpm add @tunbudi06/inertia-route-helper
npm install @tunbudi06/inertia-route-helper
Just pass props - the helper automatically finds initialPage.props.baseUrl:
// resources/js/app.tsx (React) or resources/js/app.ts (Vue/Svelte)
import { createInertiaApp } from '@inertiajs/react'; // or vue3/svelte
import { initRouteHelper } from '@tunbudi06/inertia-route-helper/init';
createInertiaApp({
resolve: (name) => {
// Your page resolver
},
setup({ el, App, props }) {
// Just pass props - super simple!
initRouteHelper(props);
// Mount your app...
},
});
ðĄ New in v2.0: Import initialization functions from
/initfor cleaner separation. Route helper functions from main import.
Share your base URL with Inertia:
// app/Http/Middleware/HandleInertiaRequests.php
public function share(Request $request): array
{
return array_merge(parent::share($request), [
'baseUrl' => rtrim(config('app.url'), '/'),
]);
}
import { route, routeUrl, buildRoute } from '@tunbudi06/inertia-route-helper';
import { dashboard, profile } from '@/routes'; // Your Ziggy/Wayfinder routes
// Get the full route object with absolute URL
const dashboardRoute = route(dashboard());
console.log(dashboardRoute.url); // https://example.com/dashboard
// Get just the URL string
const profileUrl = routeUrl(profile({ id: 123 }));
console.log(profileUrl); // https://example.com/profile/123
// Build route with query parameters
const searchUrl = buildRoute('/search', {
query: { q: 'inertia', page: 2 },
fragment: 'results'
});
console.log(searchUrl); // https://example.com/search?q=inertia&page=2#results
initRouteHelper(data)Initialize the route helper with Inertia props. Automatically extracts baseUrl from various data structures.
ðĄ Import from
/init: This function is available from@tunbudi06/inertia-route-helper/initfor better tree shaking.
Parameters:
data - Can be props from createInertiaApp, Svelte $page store, or any object containing baseUrlSupports:
props.initialPage.props.baseUrl (React/Vue createInertiaApp)page.props.baseUrl (Svelte $page store)data.baseUrl (direct object)import { initRouteHelper } from '@tunbudi06/inertia-route-helper/init';
// React/Vue - Pass props from createInertiaApp
createInertiaApp({
setup({ el, App, props }) {
initRouteHelper(props);
}
});
// Svelte - Can use props or $page
import { page } from '@inertiajs/svelte';
initRouteHelper(props); // or initRouteHelper($page)
route(routeDefinition)Transform a route definition to include absolute URL with base URL prepended.
Parameters:
routeDefinition - Route object with url property (from Ziggy/Wayfinder)Returns: Route object with absolute URL
import { route } from '@tunbudi06/inertia-route-helper';
const dashboardRoute = route({ url: '/dashboard', method: 'GET' });
// { url: 'https://example.com/dashboard', method: 'GET' }
routeUrl(routeDefinition)Get just the URL string from a route definition.
Parameters:
routeDefinition - Route object with url propertyReturns: Absolute URL string
import { routeUrl } from '@tunbudi06/inertia-route-helper';
import { users } from '@/routes';
const url = routeUrl(users.show({ id: 123 }));
// 'https://example.com/users/123'
buildRoute(path, options?)Build a complete URL with query parameters and fragment.
Parameters:
path - Base path (e.g., '/search')options - Optional configurationquery? - Query parameters objectfragment? - Fragment/hash identifierabsolute? - Whether to include base URL (default: true)Returns: Complete URL string
import { buildRoute } from '@tunbudi06/inertia-route-helper';
// With query parameters
const url = buildRoute('/search', {
query: { q: 'test', page: 2 },
fragment: 'results'
});
// 'https://example.com/search?q=test&page=2#results'
// Relative URL
const relativeUrl = buildRoute('/api/users', { absolute: false });
// '/api/users'
// With array parameters
const filtersUrl = buildRoute('/products', {
query: { tags: ['new', 'featured'], colors: ['red', 'blue'] }
});
// 'https://example.com/products?tags[]=new&tags[]=featured&colors[]=red&colors[]=blue'
makeRoute(definition)Build route from a RouteDefinition object (convenience wrapper).
Parameters:
definition - Route definition object with url, query, and fragmentReturns: Complete URL string
import { makeRoute } from '@tunbudi06/inertia-route-helper';
const url = makeRoute({
url: '/posts',
query: { status: 'published' },
fragment: 'list'
});
// 'https://example.com/posts?status=published#list'
isCurrentRoute(path, useHost?, exact?)Check if a path matches the current browser location.
Parameters:
path - Path to check (e.g., '/dashboard')useHost? - Whether to include the baseUrl or not (default: false)exact? - Whether to match exactly (default: false for partial match)Returns: true if path matches current location
import { isCurrentRoute } from '@tunbudi06/inertia-route-helper';
// Current URL: https://example.com/dashboard/settings
isCurrentRoute('/dashboard'); // true (partial match)
isCurrentRoute('/dashboard', false, true); // false (not exact)
isCurrentRoute('/dashboard/settings', false, true); // true (exact match)
// With useHost=true (check against full URL)
isCurrentRoute('/dashboard', true); // true
isCurrentRoute('https://example.com/dashboard', true); // true
isCurrentRoute('https://example.com/dashboard/settings', true, true); // true (exact)
isCurrentRoute('https://example.com/dashboard', true, true); // false (not exact)
// Use in components for active navigation
const isActive = isCurrentRoute('/dashboard');
currentPath()Get the current pathname from browser location (SSR-safe).
Returns: Current pathname or empty string on server
import { currentPath } from '@tunbudi06/inertia-route-helper';
const path = currentPath();
// '/dashboard/settings'
currentUrl()Get the complete current URL from browser location (SSR-safe).
Returns: Full URL or empty string on server
import { currentUrl } from '@tunbudi06/inertia-route-helper';
const url = currentUrl();
// 'https://example.com/dashboard/settings?tab=profile#section'
configure(options)Configure route helper behavior globally.
Parameters:
options - Configuration objectbaseUrl? - Override base URLtrailingSlash? - Add trailing slash to URLs (default: false)validateRoutes? - Enable route validation (default: false)import { configure } from '@tunbudi06/inertia-route-helper';
configure({
baseUrl: 'https://custom-domain.com',
trailingSlash: true,
validateRoutes: false
});
setBaseUrl(url)Manually set the base URL (for testing or advanced use cases).
Parameters:
url - Base URL stringimport { setBaseUrl } from '@tunbudi06/inertia-route-helper';
setBaseUrl('https://example.com');
getBaseUrl()Get the current base URL.
Returns: Current base URL string
import { getBaseUrl } from '@tunbudi06/inertia-route-helper';
const baseUrl = getBaseUrl();
// 'https://example.com'
import { route, routeUrl } from '@tunbudi06/inertia-route-helper';
import { users, posts } from '@/routes';
// Simple route
const usersUrl = routeUrl(users());
// https://example.com/users
// Route with parameters
const userUrl = routeUrl(users.show({ user: 42 }));
// https://example.com/users/42
// Complex route with parameters
const postUrl = routeUrl(posts.edit({ post: 10, comment: 5 }));
// https://example.com/posts/10/comments/5/edit
import { buildRoute, makeRoute } from '@tunbudi06/inertia-route-helper';
// Using buildRoute
const productsUrl = buildRoute('/products', {
query: {
category: 'electronics',
sort: 'price',
order: 'desc',
page: 2
}
});
// https://example.com/products?category=electronics&sort=price&order=desc&page=2
// With array parameters
const filtersUrl = buildRoute('/api/items', {
query: {
tags: ['featured', 'new', 'sale'],
price: [10, 100]
}
});
// https://example.com/api/items?tags[]=featured&tags[]=new&tags[]=sale&price[]=10&price[]=100
// Using makeRoute with RouteDefinition
const searchUrl = makeRoute({
url: '/search',
query: { q: 'inertia' },
fragment: 'results'
});
// https://example.com/search?q=inertia#results
import { isCurrentRoute, currentPath, currentUrl } from '@tunbudi06/inertia-route-helper';
// Check if a route is active (for navigation highlighting)
const isActive = isCurrentRoute('/dashboard'); // Partial match
const isExactActive = isCurrentRoute('/dashboard', false, true); // Exact match
const isActiveFullUrl = isCurrentRoute('https://example.com/dashboard', true); // Using full URL
// Get current path
const path = currentPath();
console.log(path); // /dashboard/settings
// Get current full URL
const url = currentUrl();
console.log(url); // https://example.com/dashboard/settings
import { configure } from '@tunbudi06/inertia-route-helper';
// Configure the route helper
configure({
baseUrl: 'https://custom-domain.com', // Override base URL
trailingSlash: true, // Add trailing slashes to URLs
validateRoutes: true // Enable route validation (future feature)
});
import { setBaseUrl, getBaseUrl } from '@tunbudi06/inertia-route-helper';
// Manually set base URL (useful for testing or special cases)
setBaseUrl('https://staging.example.com');
// Get the current base URL
const base = getBaseUrl();
console.log(base); // https://staging.example.com
route<T>(routeDefinition: T): TWraps a route definition and adds the absolute URL.
const userRoute = route(users.show({ id: 1 }));
routeUrl<T>(routeDefinition: T): stringReturns just the absolute URL string for a route.
const url = routeUrl(dashboard());
buildRoute(path: string, options?): stringBuild a complete URL with query parameters and fragment.
const url = buildRoute('/search', {
query: { q: 'hello' },
fragment: 'top',
absolute: true // default
});
makeRoute(definition: RouteDefinition): stringEnhanced route builder with full feature support.
const url = makeRoute({
url: '/products',
query: { category: 'books' },
fragment: 'featured'
});
isCurrentRoute(path: string, useHost?: boolean, exact?: boolean): booleanCheck if a route matches the current path.
const isActive = isCurrentRoute('/dashboard'); // Partial match (pathname only)
const isExact = isCurrentRoute('/dashboard', false, true); // Exact match (pathname only)
const isActiveFullUrl = isCurrentRoute('https://example.com/dashboard', true); // Using full URL
currentPath(): stringGet the current route path (relative).
const path = currentPath(); // '/dashboard/profile'
currentUrl(): stringGet the current full URL.
const url = currentUrl(); // 'https://example.com/dashboard/profile'
configure(options: RouteHelperConfig): voidConfigure the route helper behavior.
configure({
baseUrl: 'https://example.com',
trailingSlash: true,
validateRoutes: false
});
setBaseUrl(url: string): voidManually set the base URL.
setBaseUrl('https://api.example.com');
getBaseUrl(): stringGet the current base URL.
const base = getBaseUrl();
import { Link } from '@inertiajs/react';
import { routeUrl, isCurrentRoute } from '@tunbudi06/inertia-route-helper';
import { dashboard, profile, settings } from '@/routes';
export function Navigation() {
return (
<nav>
<Link
href={routeUrl(dashboard())}
className={isCurrentRoute('/dashboard') ? 'active' : ''}
>
Dashboard
</Link>
<Link
href={routeUrl(profile({ id: userId }))}
className={isCurrentRoute(`/profile/${userId}`, false, true) ? 'active' : ''}
>
Profile
</Link>
<Link href={routeUrl(settings())}>
Settings
</Link>
</nav>
);
}
<script setup lang="ts">
import { Link } from '@inertiajs/vue3';
import { routeUrl, isCurrentRoute, buildRoute } from '@tunbudi06/inertia-route-helper';
import { posts, search } from '@/routes';
const searchQuery = ref('');
const handleSearch = () => {
const url = buildRoute('/search', {
query: { q: searchQuery.value, type: 'posts' }
});
router.visit(url);
};
</script>
<template>
<div>
<Link
:href="routeUrl(posts())"
:class="{ active: isCurrentRoute('/posts') }"
>
All Posts
</Link>
<form @submit.prevent="handleSearch">
<input v-model="searchQuery" placeholder="Search..." />
<button type="submit">Search</button>
</form>
</div>
</template>
<script lang="ts">
import { router } from '@inertiajs/svelte';
import { routeUrl, buildRoute, isCurrentRoute } from '@tunbudi06/inertia-route-helper';
import { products, categories } from '@/routes';
let selectedCategory = 'all';
function filterProducts(category: string) {
const url = buildRoute('/products', {
query: { category, sort: 'popular' }
});
router.visit(url);
}
</script>
<nav>
<a
href={routeUrl(products())}
class:active={isCurrentRoute('/products')}
>
Products
</a>
<button on:click={() => filterProducts('electronics')}>
Electronics
</button>
</nav>
This package is perfect for Laravel apps deployed in subfolders:
// .env
APP_URL=https://example.com/my-app
// The package automatically handles this!
import { routeUrl } from '@tunbudi06/inertia-route-helper';
import { dashboard } from '@/routes';
const url = routeUrl(dashboard());
// Correctly returns: https://example.com/my-app/dashboard
// Not just: https://example.com/dashboard
Full TypeScript support with comprehensive type definitions:
import type {
RouteDefinition,
QueryParams,
RouteHelperConfig
} from '@tunbudi06/inertia-route-helper';
const route: RouteDefinition = {
url: '/users',
query: { page: 1, limit: 10 },
fragment: 'list'
};
const query: QueryParams = {
search: 'hello',
filters: ['active', 'verified'],
page: 1
};
const config: RouteHelperConfig = {
baseUrl: 'https://example.com',
trailingSlash: false
};
Contributions are welcome! Please feel free to submit a Pull Request.
git checkout -b feature/amazing-feature)git commit -m 'Add some amazing feature')git push origin feature/amazing-feature)MIT ÂĐ TUNBudi06
Made with âĪïļ by TUNBudi06