Skip to content

Instantly share code, notes, and snippets.

@tillsanders
Created June 30, 2021 10:18
Show Gist options
  • Save tillsanders/b717711b3adb54da81a1bcb8e21ad14c to your computer and use it in GitHub Desktop.
Save tillsanders/b717711b3adb54da81a1bcb8e21ad14c to your computer and use it in GitHub Desktop.
Base64 Encode/Decode Plugin for Nuxt.js + TypeScript

Base64 Encode/Decode Plugin for Nuxt.js + TypeScript

I was looking for an easy way to do Base64 encoding/decoding in Nuxt.js while using SSR (server-side rendering). It's not really a big deal, but I didn't find a quick solution. So here is a tiny plugin to help with that. Just drop it into your /plugins/ directory and reference it in the nuxt.config.ts:

  plugins: [
    { src: '~/plugins/base64.ts' },
  ]
import { Plugin } from '@nuxt/types'
function encodeBase64 (value: string): string {
if (process.client) {
return window.btoa(unescape(encodeURIComponent(value)))
} else {
return Buffer.from(value, 'ascii').toString('base64')
}
}
function decodeBase64 (value: string): string {
if (process.client) {
return decodeURIComponent(escape(window.atob(value)))
} else {
return Buffer.from(value, 'base64').toString('ascii')
}
}
declare module 'vue/types/vue' {
interface Vue {
$encodeBase64: (value: string) => string,
$decodeBase64: (value: string) => string
}
}
declare module '@nuxt/types' {
// nuxtContext.app.$lines inside asyncData, fetch, plugins, middleware, nuxtServerInit
interface NuxtAppOptions {
$encodeBase64: (value: string) => string,
$decodeBase64: (value: string) => string
}
// nuxtContext.$lines
interface Context {
$encodeBase64: (value: string) => string,
$decodeBase64: (value: string) => string
}
}
declare module 'vuex/types/index' {
// this.$lines inside Vuex stores
// eslint-disable-next-line
interface Store<S> {
$encodeBase64: (value: string) => string,
$decodeBase64: (value: string) => string
}
}
const base64Plugin: Plugin = (_context, inject) => {
inject('encodeBase64', encodeBase64)
inject('decodeBase64', decodeBase64)
}
export default base64Plugin
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment