Example: Basic Code to use NodeJS Split SDK 10.15.0 or latest with Vue Framework and Nuxt Library using Server Side Rendering.
Environment:
- Nuxt 2.0.0
- Node 10.15.3
- Vue 2.6.12
Steps to run the app:
1. Download the zip file from the link below and extract it in new folder.
2. Run the following command to install dependencies:
npm install
3. The Split NodeJS SDK is loaded as a Vue plugin in /plugins/splitAPI.server.js and the file name contains "server" to force load the SDK only on server side.
4. To initialize the Split factory object as singleton (only once), we stored the factory object in Vue instance property, and then reuse the same property afterwards. Make sure to replace the 'SDK API Key' with a valid API Key type "sdk".
import Vue from 'vue'
import { SplitFactory } from '@splitsoftware/splitio';
if (!Vue.prototype.hasOwnProperty('$factory')) {
let factory = SplitFactory({
core: {
authorizationKey: 'SDK API KEY',
},
});
factory.Logger.enable();
Vue.prototype.$factory = factory
}
export default (context, inject) => {
inject('factory', Vue.prototype.$factory)
context.$factory = Vue.prototype.$factory
}
5. The code below is located in store/index.js and is used to calculate the treatment. We use "client.ready()", which is a promise that the client object resolves when the SDK is ready and will reject if the timeout is reached.
Note: Be sure to replace the user key and split name in the example below:
import Vuex from 'vuex'
export const state = () => ({
treatment: null
})
export const mutations = {
SET_TREATMENT(state, treatment){
state.treatment = treatment
}
}
export const actions = {
async nuxtServerInit({ commit }) {
let client = this.$factory.client();
await client.ready()
let treatment = client.getTreatment('john', 'sample_feature');
commit('SET_TREATMENT', treatment);
}
}
6. To run the sample app, do the following:
npm run dev
Comments
0 comments
Please sign in to leave a comment.