# NavigationHistory [![Build Status](]( [![Hex Version](]( [![Hex docs](](

A plug to keep track of user navigation history using sessions.
This can be useful for example to redirect the user back to the previous page,
or to redirect after a login when the user tried to access a page without being

## Installation

Add `navigation_history` to your list of dependencies in `mix.exs`:

def deps do
  [{:navigation_history, "~> 0.3"}]

## Usage

To keep track of the navigation, add the `NavigationHistory.Tracker` plug.
For example, in a Phoenix application, your pipeline could become:

pipeline :browser do
  plug :accepts, ["html"]
  plug :fetch_session
  plug :fetch_flash
  plug :protect_from_forgery
  plug :put_secure_browser_headers
  plug NavigationHistory.Tracker

You can then retrieve the paths the user navigated to by using

NavigationHistory.last_path(conn) # will return the last navigated path or nil
NavigationHistory.last_path(conn, 1) # will return the second last navigated path
NavigationHistory.last_path(conn, default: "/") # will return the last path or "/"
NavigationHistory.last_paths(conn) # will return a list of the last navigated paths
NavigationHistory.last_path(session) # instead of passing a conn, can also pass a session

For example, to redirect the user to the last navigated path in Phoenix, you can use
a helper like this

def redirect_back(conn, opts \\ []) do
  Phoenix.Controller.redirect(conn, to: NavigationHistory.last_path(conn, opts))

# you can then write
redirect_back(conn, default: "/")

Take a look at [this conversation]( in Phoenix for more info about redirecting back.

## Configuration

There are a few options that can be used with the plug:

  * `excluded_paths` - The list of paths which should not be tracked.
      For example, `/login` or similar for a lot of apps.
      Defaults to `[]`
  * `included_paths` - Limits list the paths to be tracked when set.
      `excluded_paths` is ignored if set.
  * `methods` - The list methods which should be tracked.
      Defaults to `["GET"]`
  * `history_size` - The number of history entries to track in `last_paths`.
      Defaults to `10`.
  * `key` - The key used to track the navigation.
      It can also be passed to `last_path` and `last_paths` to retrieve the paths for the
      relevant key.
      Defaults to `"default"`.
  * `accept_duplicates` - By default, if the same URL is repeated, it is ignored, unless this
      option is set to `true`.
      Defaults to `false`.

### Example

plug NavigationHistory.Tracker, excluded_paths: ["/login", ~r(/admin.*)]
plug NavigationHistory.Tracker, included_paths: [~r(/admin.*)], key: "admin", history_size: 5

# which an be used
NavigationHistory.last_path(conn) # from default history
NavigationHistory.last_path(conn, key: "admin") # from admin history