Powerful routing helper for Inertia.js v2 & v3 applications
Work seamlessly with Laravel Ziggy or Wayfinder routes, with full support for subfolder deployments, query parameters, subfolder path deduplication, and route validation.
Features β’ Installation β’ Usage β’ API Reference β’ Examples
- π Absolute URL Generation - Automatically prepends your base URL to all routes
- π Subfolder Deployment Support - Perfect for apps deployed in subfolders
- π Query Parameters - Build routes with query strings effortlessly
- π― Route Validation - Check if routes match the current path
- π¨ TypeScript First - Full type safety and IntelliSense support
- β‘ Inertia.js v2 & v3 - Works seamlessly with both versions
- π Subfolder Deduplication - Prevents URL doubling when routes already include the subfolder path (essential for Inertia v3 deployed apps)
- π SSR Safe - Works perfectly with server-side rendering
- πͺΆ Lightweight - Minimal bundle size
- βοΈ Configurable - Customize behavior to fit your needs
- π¦ Modular Architecture - One function per file for easy reading
- π§ Separate Init Module -
/initimport for setup, main import for usage - β Fully Tested - Comprehensive test coverage
- π Complete Documentation - Detailed API reference and examples
- Quick Start Guide - Get started in 5 minutes
- Complete API Reference - Full documentation of all functions
- Examples - Framework-specific examples
- CHANGELOG - Version history and updates
npm install @tunbudi06/inertia-route-helperyarn add @tunbudi06/inertia-route-helperpnpm add @tunbudi06/inertia-route-helpernpm install @tunbudi06/inertia-route-helperJust 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...
},
});π‘ Import from
/init: 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#resultsInitialize 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 fromcreateInertiaApp, Svelte$pagestore, or any object containing baseUrl
Supports:
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)Transform a route definition to include absolute URL with base URL prepended.
Parameters:
routeDefinition- Route object withurlproperty (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' }Get just the URL string from a route definition.
Parameters:
routeDefinition- Route object withurlproperty
Returns: 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'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'Build route from a RouteDefinition object (convenience wrapper).
Parameters:
definition- Route definition object withurl,query, andfragment
Returns: 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'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');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'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 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
});Manually set the base URL (for testing or advanced use cases).
Parameters:
url- Base URL string
import { setBaseUrl } from '@tunbudi06/inertia-route-helper';
setBaseUrl('https://example.com');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/editimport { 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#resultsimport { 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/settingsimport { 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.comWraps a route definition and adds the absolute URL.
const userRoute = route(users.show({ id: 1 }));Returns just the absolute URL string for a route.
const url = routeUrl(dashboard());Build a complete URL with query parameters and fragment.
const url = buildRoute('/search', {
query: { q: 'hello' },
fragment: 'top',
absolute: true // default
});Enhanced route builder with full feature support.
const url = makeRoute({
url: '/products',
query: { category: 'books' },
fragment: 'featured'
});Check 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 URLGet the current route path (relative).
const path = currentPath(); // '/dashboard/profile'Get the current full URL.
const url = currentUrl(); // 'https://example.com/dashboard/profile'Configure the route helper behavior.
configure({
baseUrl: 'https://example.com',
trailingSlash: true,
validateRoutes: false
});Manually set the base URL.
setBaseUrl('https://api.example.com');Get 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/dashboardWhen deploying in subfolders, some routing libraries (Ziggy, Wayfinder) may generate route paths that already include the subfolder path. This helper automatically detects and deduplicates to prevent URL doubling:
// baseUrl = 'http://localhost/myapp'
// Route already includes subfolder β automatically deduplicated
const url = routeUrl({ url: '/myapp/dashboard' });
// β
'http://localhost/myapp/dashboard'
// β Not: 'http://localhost/myapp/myapp/dashboard'
// Route without subfolder β works normally
const url2 = routeUrl({ url: '/dashboard' });
// 'http://localhost/myapp/dashboard'This is especially important for Inertia v3 apps where the base URL's subfolder path may be included in route definitions by default.
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.
- Fork the repository
- Create your feature branch (
git checkout -b feature/amazing-feature) - Commit your changes (
git commit -m 'Add some amazing feature') - Push to the branch (
git push origin feature/amazing-feature) - Open a Pull Request
MIT Β© TUNBudi06
- Built for Inertia.js v2 & v3
- Works with Ziggy and Wayfinder
- Inspired by the Laravel and Inertia.js communities
Made with β€οΈ by TUNBudi06