Skip to content

Add request interceptor support #13

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Jun 7, 2021
Merged

Add request interceptor support #13

merged 1 commit into from
Jun 7, 2021

Conversation

kirillplatonov
Copy link
Contributor

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 (hotwired/turbo#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 marcelolx self-assigned this Jun 6, 2021
Copy link
Collaborator

@marcelolx marcelolx left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM

@marcelolx marcelolx removed their assignment Jun 6, 2021
@marcelolx
Copy link
Collaborator

@kirillplatonov Can you please resolve the conflicts?

@kirillplatonov
Copy link
Contributor Author

@marcelolx Yep, updated.

Copy link
Collaborator

@marcelolx marcelolx left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM

@marcelolx marcelolx merged commit 72bb933 into rails:main Jun 7, 2021
@marcelolx
Copy link
Collaborator

marcelolx commented Jun 7, 2021

Thanks @kirillplatonov

@lonroth
Copy link

lonroth commented Jun 10, 2021

Nice one @kirillplatonov ! 👏

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

3 participants