rails / request.js

MIT License
390 stars 28 forks source link

Add request interceptor support #13

Closed kirillplatonov closed 3 years ago

kirillplatonov commented 3 years ago

Problem

Modern embedded Shopify apps are built with JWT session tokens that need to be passed to every server request. The token needs to be fetched right before the request. Without token, all Ajax requests to the server will fail.

Solution

This PR introduces request interceptor support. It allows inserting the async function between every fetch request. Inside this function, you can do some preparation for requests and add custom headers. I already proposed the same API for Turbo (https://github.com/hotwired/turbo/pull/177).

Example usage

import { RequestInterceptor } from '@rails/request.js'
// ...

// Set interceptor
RequestInterceptor.register(async (request) => {
  const token = await getSessionToken(window.app)
  request.addHeader('Authorization', `Bearer ${token}`)
})

// Reset interceptor
RequestInterceptor.reset()
marcelolx commented 3 years ago

@kirillplatonov Can you please resolve the conflicts?

kirillplatonov commented 3 years ago

@marcelolx Yep, updated.

marcelolx commented 3 years ago

Thanks @kirillplatonov

lonroth commented 3 years ago

Nice one @kirillplatonov ! 👏