navigate

Programmatically navigate to routes with dynamic parameters, query strings, and history control.

API

function navigate(
  pattern: string,
  params?: Record<string, string>,
  query?: Record<string, string>,
  opts?: { replace?: boolean }
): void

TypeScript

The function is fully typed for parameters and opts.

// Navigate to /users/42?sort=asc
navigate(
  '/users/:id', 
  { id: '42' }, 
  { sort: 'asc' }
);

Basic Usage

Use navigate to trigger navigation from event handlers, effects, or anywhere in your application logic.

import { navigate } from "@hellajs/router";

// Navigate to a static path
navigate("/dashboard");

// Substitute route parameters
// Navigates to /posts/hello-world
navigate("/posts/:slug", { slug: "hello-world" });

// Add query parameters
// Navigates to /search?q=reactive
navigate("/search", {}, { q: "reactive" });

Key Concepts

History Management

navigate integrates with the browser’s History API, pushing new entries by default or replacing them with the replace option.

// Adds new history entry (user can go back)
navigate('/dashboard');

// Replaces current history entry (user cannot go back)
navigate('/dashboard', {}, {}, { replace: true });

Parameter Substitution

Route patterns with :param placeholders are dynamically substituted with values from the params object. You can pass either a pattern with placeholders or a final URL path. This works seamlessly with both flat and nested route structures.

// Option 1: Using pattern with parameter substitution
navigate('/users/:id/posts/:postId', {
  id: '123',
  postId: 'hello-world'
}); // Results in: /users/123/posts/hello-world

// Option 2: Using final URL directly (no substitution needed)
navigate('/users/123/posts/hello-world');

// Works with nested routes too
navigate('/admin/users/:id/edit', {
  id: '456'  
}); // Results in: /admin/users/456/edit

Query String Handling

Query parameters are automatically serialized and appended to the final URL.

navigate('/search', {}, { 
  q: 'reactive', 
  category: 'frameworks',
  page: '2' 
}); // Results in: /search?q=reactive&category=frameworks&page=2

Important Considerations

Asynchronous Navigation

Navigation is asynchronous - the route change isn’t immediate.

// ❌ Route may not be updated yet
navigate('/dashboard');
console.log(route().path);
// ✅ Use effect for route changes
effect(() => {
  if (route().path === '/dashboard') {
    console.log('Dashboard loaded');
  }
});

Replace vs Push

Using replace: true prevents users from navigating back to the previous page.

// ✅ Normal navigation - can go back
navigate('/new-page');
// ✅ Replace - overwrites history entry
navigate('/redirect', {}, {}, { replace: true });

Parameter Validation

Invalid parameter keys (not matching route pattern) are ignored.

// ✅ Correct parameter key
navigate('/users/:id', { id: '123' });
// ❌ Wrong key, param not substituted
navigate('/users/:id', { userId: '123' });