Security News
NIST Misses 2024 Deadline to Clear NVD Backlog
NIST has failed to meet its self-imposed deadline of clearing the NVD's backlog by the end of the fiscal year. Meanwhile, CVE's awaiting analysis have increased by 33% since June.
The history package is a JavaScript library that lets you manage session history anywhere JavaScript runs. It provides a minimal API that lets you manage the history stack, navigate, and persist state between sessions. It is commonly used in conjunction with libraries like React Router but can be used standalone as well.
Manage session history
This feature allows you to create a history object and manipulate the browser's session history by pushing new entries onto the history stack.
const { createBrowserHistory } = require('history');
const history = createBrowserHistory();
history.push('/home', { some: 'state' });
Navigate programmatically
This feature enables you to navigate through the history stack programmatically, either going back or forward.
history.go(-1); // Go back one entry in the history stack
history.goForward(); // Go forward one entry in the history stack
Listen for changes to the current location
This feature allows you to listen for changes in the current location, which is useful for reacting to navigation events.
const unlisten = history.listen((location, action) => {
console.log(action, location.pathname, location.state);
});
// To stop listening
unlisten();
Persist state between sessions
This feature allows you to push state onto the history stack and access it later, which is useful for persisting information across sessions without using local storage or cookies.
history.push('/location', { user: '12345' });
// The state can be accessed later
const location = history.location;
const state = location.state; // { user: '12345' }
React Router is a collection of navigational components that compose declaratively with your application. It provides bindings to the history library, making it easier to use with React applications. It is more feature-rich and tailored specifically for React, compared to the more general-purpose history package.
Vue Router is the official router for Vue.js. It deeply integrates with Vue.js core to make building Single Page Applications with Vue.js a breeze. It provides similar functionalities for managing navigation and history in Vue applications, analogous to what history does for more general JavaScript applications.
Reach Router is a small, simple router for React that borrows from the ideas of the history package. It provides easy route definition and navigation but has been officially replaced by React Router as of version 6.
Navigo is a simple vanilla JavaScript router with a similar API to history. It provides a powerful router with a small footprint that does not necessarily rely on the history API provided by the browser.
history
is a JavaScript library that lets you easily manage session history anywhere JavaScript runs. history
abstracts away the differences in various environments and provides a minimal API that lets you manage the history stack, navigate, confirm navigation, and persist state between sessions.
Using npm:
$ npm install --save history
Then with a module bundler like webpack, use as you would anything else:
// using an ES6 transpiler, like babel
import createHistory from 'history/createBrowserHistory'
// not using an ES6 transpiler
var createHistory = require('history').createBrowserHistory
The UMD build is also available on unpkg:
<script src="https://unpkg.com/history/umd/history.min.js"></script>
You can find the library on window.History
.
history
provides 3 different methods for creating a history
object, depending on your environment.
createBrowserHistory
is for use in modern web browsers that support the HTML5 history API (see cross-browser compatibility)createMemoryHistory
is used as a reference implementation and may also be used in non-DOM environments, like React NativecreateHashHistory
is for use in legacy web browsersDepending on the method you want to use to keep track of history, you'll import
(or require
) one of these methods directly from the root directory (i.e. history/createBrowserHistory
). The remainder of this document uses the term createHistory
to refer to any of these implementations.
Basic usage looks like this:
import createHistory from 'history/createBrowserHistory'
const history = createHistory()
// Get the current location.
const location = history.location
// Listen for changes to the current location.
const unlisten = history.listen((location, action) => {
console.log(action, location.path, location.state)
})
// Use push, replace, and go to navigate around.
history.push('/home', { some: 'state' })
// To stop listening, call the function returned from listen().
unlisten()
The options that each create
method takes, along with its default values, are:
createBrowserHistory({
basename: '', // The base URL of the app (see below)
forceRefresh: false, // Set true to force full page refreshes
keyLength: 6, // The length of location.key
// A function to use to confirm navigation with the user (see below)
getUserConfirmation: (message, callback) => callback(window.confirm(message))
})
createMemoryHistory({
initialEntries: [ '/' ], // The initial URLs in the history stack
initialIndex: 0, // The starting index in the history stack
keyLength: 6, // The length of location.key
// A function to use to confirm navigation with the user. Required
// if you return string prompts from transition hooks (see below)
getUserConfirmation: null
})
createHashHistory({
basename: '', // The base URL of the app (see below)
hashType: 'slash', // The hash type to use (see below)
// A function to use to confirm navigation with the user (see below)
getUserConfirmation: (message, callback) => callback(window.confirm(message))
})
Each history
object has the following properties:
length
- The number of entries in the history stacklocation
- The current location (see below)action
- The current navigation action (see below)Additionally, createMemoryHistory
provides index
and entries
properties that let you inspect the history stack.
You can listen for changes to the current location using history.listen
:
history.listen((location, action) => {
console.log(`The current URL is ${location.path}`)
console.log(`The last navigation action was ${action}`)
})
The location
object implements a subset of the window.location
interface, including:
pathname
- The path of the URLsearch
- The URL query stringhash
- The URL hash fragmentLocations may also have the following properties:
state
- Some extra state for this location that does not reside in the URL (supported in createBrowserHistory
and createMemoryHistory
)key
- A unique string representing this location (supported in createBrowserHistory
and createMemoryHistory
)The action
is one of PUSH
, REPLACE
, or POP
depending on how the user got to the current URL.
history
objects may be used programmatically change the current location using the following methods:
push(to)
replace(to)
go(n)
goBack()
goForward()
canGo(n)
(only in createMemoryHistory
)The push
and replace
methods accept a single to
argument. This is either:
path
(including the query string and hash fragment) OR{ pathname, search, hash, state }
// Push a new entry onto the history stack.
history.push('/home')
// Replace the current entry on the history stack.
history.replace('/profile')
// Push a new entry with state onto the history stack. State may
// be any arbitrary data tied to a particular location. Unlike the
// query string, location state does not appear in the URL.
history.push({
pathname: '/about',
search: '?the=query',
state: { some: 'state' }
})
// Go back to the previous history entry. The following
// two lines are synonymous.
history.go(-1)
history.goBack()
Note: Location state is only supported in createBrowserHistory
and createMemoryHistory
.
history
lets you register a prompt message that will be shown to the user before location listeners are notified. This allows you to make sure the user wants to leave the current page before they navigate away.
// Register a simple prompt message that will be shown the
// user before they navigate away from the current page.
const unblock = history.block('Are you sure you want to leave this page?')
// Or use a function that returns the message when it's needed.
history.block((location, action) => {
// The location and action arguments indicate the location
// we're transitioning to and how we're getting there.
// A common use case is to prevent the user from leaving the
// page if there's a form they haven't submitted yet.
if (input.value !== '')
return 'Are you sure you want to leave this page?'
})
// To stop blocking transitions, call the function returned from block().
unblock()
Note: You'll need to provide a getUserConfirmation
function to use this feature with createMemoryHistory
(see below).
By default, window.confirm
is used to show prompt messages to the user. If you need to override this behavior (or if you're using createMemoryHistory
, which doesn't assume a DOM environment), provide a getUserConfirmation
function when you create your history object.
const history = createHistory({
getUserConfirmation(message, callback) {
// Show some custom dialog to the user and call
// callback(true) to continue the transiton, or
// callback(false) to abort it.
}
})
If all the URLs in your app are relative to some other "base" URL, use the basename
option. This option transparently adds the given string to the front of all URLs you use.
const history = createHistory({
basename: '/the/base'
})
history.push('/home') // URL is now /the/base/home
Note: This feature is not suppported in createMemoryHistory
.
By default createBrowserHistory
uses HTML5 pushState
and replaceState
to prevent reloading the entire page from the server while navigating around. If instead you would like to reload as the URL changes, use the forceRefresh
option.
const history = createBrowserHistory({
forceRefresh: true
})
By default createHashHistory
uses a leading slash in hash-based URLs. You can use the hashType
option to use a different hash formatting.
const history = createHashHistory({
hashType: 'slash' // the default
})
history.push('/home') // window.location.hash is #/home
const history = createHashHistory({
hashType: 'noslash' // Omit's the leading slash
})
history.push('/home') // window.location.hash is #home
const history = createHashHistory({
hashType: 'hashbang' // Google's legacy AJAX URL format
})
history.push('/home') // window.location.hash is #!/home
A big thank-you to Dan Shaw for letting us use the history
npm package name! Thanks Dan!
Also, thanks to BrowserStack for providing the infrastructure that allows us to run our build in real browsers.
FAQs
Manage session history with JavaScript
The npm package history receives a total of 6,537,446 weekly downloads. As such, history popularity was classified as popular.
We found that history demonstrated a not healthy version release cadence and project activity because the last version was released a year ago. It has 1 open source maintainer collaborating on the project.
Did you know?
Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.
Security News
NIST has failed to meet its self-imposed deadline of clearing the NVD's backlog by the end of the fiscal year. Meanwhile, CVE's awaiting analysis have increased by 33% since June.
Security News
Cloudflare has launched a setup wizard allowing users to easily create and manage a security.txt file for vulnerability disclosure on their websites.
Security News
The Socket Research team breaks down a malicious npm package targeting the legitimate DOMPurify library. It uses obfuscated code to hide that it is exfiltrating browser and crypto wallet data.