Skip to content
On this page

useJwt

Category
Export Size
359 B
Package
@vueuse/integrations
Last Changed
7 months ago

Wrapper for jwt-decode.

Demo

Header

{
  "alg": "HS256",
  "typ": "JWT"
}

Payload

{
  "sub": "1234567890",
  "iat": 1516239022
}
Available in the @vueuse/integrations add-on.

Install

bash
npm install jwt-decode
npm install jwt-decode

Usage

typescript
import { defineComponent } from 'vue'
import { useJwt } from '@vueuse/integrations/useJwt'

export default defineComponent({
  setup() {
    const encodedJwt = ref('eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwiaWF0IjoxNTE2MjM5MDIyfQ.L8i6g3PfcHlioHCCPURC9pmXT7gdJpx3kOoyAfNUwCc')
    const { header, payload } = useJwt(encodedJwt)

    return { header, payload }
  },
})
import { defineComponent } from 'vue'
import { useJwt } from '@vueuse/integrations/useJwt'

export default defineComponent({
  setup() {
    const encodedJwt = ref('eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwiaWF0IjoxNTE2MjM5MDIyfQ.L8i6g3PfcHlioHCCPURC9pmXT7gdJpx3kOoyAfNUwCc')
    const { header, payload } = useJwt(encodedJwt)

    return { header, payload }
  },
})

Type Declarations

typescript
export interface UseJwtOptions<Fallback> {
  /**
   * Value returned when encounter error on decoding
   *
   * @default null
   */
  fallbackValue?: Fallback
  /**
   * Error callback for decoding
   */
  onError?: (error: unknown) => void
}
export interface UseJwtReturn<Payload, Header, Fallback> {
  header: ComputedRef<Header | Fallback>
  payload: ComputedRef<Payload | Fallback>
}
/**
 * Reactive decoded jwt token.
 *
 * @see https://vueuse.org/useJwt
 * @param jwt
 */
export declare function useJwt<
  Payload extends object = JwtPayload,
  Header extends object = JwtHeader,
  Fallback = null
>(
  encodedJwt: MaybeComputedRef<string>,
  options?: UseJwtOptions<Fallback>
): UseJwtReturn<Payload, Header, Fallback>
export interface UseJwtOptions<Fallback> {
  /**
   * Value returned when encounter error on decoding
   *
   * @default null
   */
  fallbackValue?: Fallback
  /**
   * Error callback for decoding
   */
  onError?: (error: unknown) => void
}
export interface UseJwtReturn<Payload, Header, Fallback> {
  header: ComputedRef<Header | Fallback>
  payload: ComputedRef<Payload | Fallback>
}
/**
 * Reactive decoded jwt token.
 *
 * @see https://vueuse.org/useJwt
 * @param jwt
 */
export declare function useJwt<
  Payload extends object = JwtPayload,
  Header extends object = JwtHeader,
  Fallback = null
>(
  encodedJwt: MaybeComputedRef<string>,
  options?: UseJwtOptions<Fallback>
): UseJwtReturn<Payload, Header, Fallback>

Source

SourceDemoDocs

Contributors

Anthony Fu
Curt Grimes
Jelf
Alex Kozack
lstoeferle

Changelog

v8.9.3 on 7/14/2022
d9dad - fix!: rename type JwtOptions to UseJwtOptions and JwtResult to UseJwtReturn (#1899)
v8.9.1 on 7/8/2022
a9ccc - feat(all): use MaybeComputedRef (#1768)

Released under the MIT License.