0.5.0 • Published 2 months ago

trpc-token-refresh-link v0.5.0

Weekly downloads
-
License
-
Repository
github
Last release
2 months ago

tRPC Token Refresh Link

| Seamlessly update your JWT access token right before it expires.

  • ✅ Works with batching
  • ✅ Works with many requests at once. Will only do one token refresh request
  • ✅ Works with tRPC v10

Demo

This demo shows how the link preserves batching and only does one request to renew the token:

shot-A5GEaVUB

Installation

npm install trpc-token-refresh-link

Implementation

import { tokenRefreshLink } from "trpc-token-refresh-link"

tokenRefreshLink({
	tokenRefreshNeeded: () => boolean,
	fetchAccessToken: async () => void
}),

Example

...
links: [
	tokenRefreshLink({
		// access to the original tRPC query operation object
		// is accessible on both methods
		tokenRefreshNeeded: (query) => {
			// on every request, this function is called

			const token = ... // get the token from localstorage or cookies

			if(query.path.includes(/* A route that does not need tokens */)){
				return false
			}

			if(/* There is no token */){
				return false
			}

			if(/* Token is valid */){
				return false
			}

			if(/* Token is expired or expires soon (in 10 seconds) */){
				return true
			}

			// Return `false` as default statement
			return false
		},
		fetchAccessToken: async (query) => {
			// if true is returned from tokenRefreshNeeded, this function will be called

			// do your magic to fetch a refresh token here
			// example:
			try {
				const res = (await fetch("/api/renew-token", {
						method: "POST",
				}).then((res) => res.json())) as { accessToken: string }

				saveAccessToken(res.accessToken) // save token to cookies
			} catch (err) {

				// token refreshing failed, let's log the user out
				if (err instanceof Error && err.message.includes("401")) {
						clearAccessToken()
						location.reload()

						// can also do more precise logs using the original object
						console.log(`Token failed blocking the ${query.path} ${query.type}.`)
				}
			}
		},
	}),
	httpLink({
		url,
	})
],
...

Philosophy

This library calculates the expiration time for the access token before sending it to the server.

This means we can refresh the token in advance, not requiring the roundtrip to the server for that.

This approach means that you need to have a way to read and decode the access token on the client. If you use a http-only access token (not available to js), this approach will not work.

Credits and similar libraries

0.5.0

2 months ago

0.4.0

1 year ago

0.2.0

1 year ago

0.1.3

2 years ago

0.1.2

2 years ago

0.1.1

2 years ago

0.1.0

2 years ago

0.0.5

2 years ago

0.0.4

2 years ago

0.0.3

2 years ago

0.0.1

2 years ago