GithubHelp home page GithubHelp logo

adarshhatkar / trpc-token-refresh-link Goto Github PK

View Code? Open in Web Editor NEW

This project forked from larskarbo/trpc-token-refresh-link

0.0 0.0 0.0 90 KB

Token Refresh Link for tRPC

License: MIT License

Shell 0.55% TypeScript 99.45%

trpc-token-refresh-link's Introduction

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

trpc-token-refresh-link's People

Contributors

larskarbo avatar epicmau5time avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.