npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

go-back-to

v1.1.1

Published

A lightweight TypeScript utility that navigates back to a specific route in browser history using the Navigation API, preserving scroll position

Readme

go-back-to

A lightweight TypeScript utility that navigates back to a specific route in browser history using the Navigation API, preserving scroll position.

Perfect for when you have a back button in your layout that needs to return users to an overview page preserving url state & scroll position, even after they've navigated through multiple nested routes. It uses the Navigation API to calculate how many steps back in the History it has to go to reach the targetPathname.

Features

  • 🎯 Navigate back to a specific pathname in history
  • 📜 Preserves scroll position automatically (thanks to Navigation API)
  • 🔍 Flexible pathname matching (exact string or custom function)
  • 🔄 Graceful fallback when Navigation API is not available
  • 📦 Zero dependencies
  • 🎨 Full TypeScript support
  • ⚛️ Works with any framework (React, Vue, Svelte, vanilla JS, etc.)

Installation

npm install go-back-to
# or
pnpm add go-back-to
# or
yarn add go-back-to

Usage

Basic Example

import { goBackTo } from "go-back-to";

// Navigate back to the home page using the Navigation API preserving url state & scroll position
goBackTo({ targetPathname: "/" });

How It Works

  1. Navigation API: The function uses the native browser Navigation API to access browser history entries. Because it relies on the browser's native API rather than framework-specific routing, it works with any framework.
  2. History Search: It searches backwards through history to find the closest entry matching your target pathname.
  3. Navigation via history.go(): Once the matching entry is found, it uses window.history.go(-stepsBack) to navigate. This approach has key advantages:
    • Preserves scroll position: The browser automatically restores the exact scroll position you were at, which is perfect for nested routes and long pages.
    • Preserves page state: Unlike window.location.href, using history.go() maintains the page's JavaScript state, form inputs, and component state.
  4. Fallback: If the Navigation API is not available or no matching entry is found, it falls back to the provided fallbackUrl, or uses targetPathname if it's a string, or uses history.back().

More Examples

With Custom Pathname Matcher

This will loop through all NavigationHistoryEntry items backwards until you return true. The matcher function receives the full URL object, allowing you to check pathname, search params, origin, and more.

import { goBackTo } from "go-back-to";

// Go back to a search page
goBackTo({
  targetPathname: (url) =>
    url.pathname.startsWith("/search"),
});

With Fallback URL

The fallbackUrl is only needed when using a custom pathname matcher function and you want to support browsers that don't support the Navigation API. When targetPathname is a string, it will automatically be used as the fallback URL if the Navigation API is unavailable or no matching entry is found.

import { goBackTo } from "go-back-to";

// When using a custom matcher, provide fallbackUrl for browsers without Navigation API support
goBackTo({
  targetPathname: (url) => url.pathname.startsWith("/dashboard"),
  fallbackUrl: "/dashboard", // Used if Navigation API is unavailable or no match found
});

With Fallback Callback (Framework Navigation)

When using with React Router, Next.js, or other frameworks, use fallbackCallback to navigate using their router instead of directly setting window.location.href:

import { goBackTo } from "go-back-to";
import { useNavigate } from "react-router"; // or your framework's navigation

const navigate = useNavigate();

goBackTo({
  targetPathname: "/",
  fallbackCallback: () => navigate("/"), // Uses React Router navigation
});

Advanced: Match by Search Params

import { goBackTo } from "go-back-to";

// Go back to any page with a specific search param
goBackTo({
  targetPathname: (url) => url.searchParams.has("filter"),
});

Usage with Next.js

Since goBackTo is a plain function, you can use it directly in event handlers. For Next.js App Router, use fallbackCallback with the router:

import { goBackTo } from "go-back-to";
import { useRouter } from "next/navigation";

function BackButton() {
  const router = useRouter();

  return (
    <button
      onClick={() =>
        goBackTo({
          targetPathname: "/",
          fallbackCallback: () => router.push("/"),
        })
      }
    >
      Go to Home
    </button>
  );
}

API

goBackTo(options?)

Navigates back to the target route in browser history.

Options

| Option | Type | Default | Description | |--------|------|---------|-------------| | targetPathname | string \| ((url: URL) => boolean) | "/" | The target pathname to go back to. Can be an exact string match or a custom matcher function that receives the full URL object. | | fallbackUrl | string | undefined | Fallback URL to navigate to if Navigation API is not available and no matching history entry is found. | | fallbackCallback | () => void | undefined | Callback function to call instead of directly setting window.location.href. Useful for framework-specific navigation (e.g., React Router, Next.js). You should handle the navigation logic and URL determination within this callback. |

Returns

void

Browser Support

The function works in all modern browsers. For browsers that don't support the Navigation API, it gracefully falls back to using window.location.href or history.back().

See Navigation API browser support on Can I Use for detailed compatibility information.

Development

This is a monorepo using pnpm workspaces. To develop:

# Install dependencies
pnpm install

# Build all packages
pnpm run build

# Run tests
pnpm run test

# Start dev mode (watch mode)
pnpm run dev

Test Apps

There are test apps available to test the function with different routers:

  • test-apps/react-router-esm - React Router (ESM)
  • test-apps/tanstack-router - TanStack Router

To run a test app:

cd test-apps/tanstack-router
pnpm dev

License

MIT