DEV Community

Eulier Gonzalez
Eulier Gonzalez

Posted on • Updated on

Working with Algolia API. Nuxt Plugins

Here we’re using Algolia to externalize our API. We’re using the most popular way to communicate with an API, Rest methodology.
We’re going to create a plugin to do this, it’s important to only copy the value of search-only, otherwise if you copy the admin-api key, you’re secret will expose to the world, and then they can read index, update, delete or much worse.
We create a plugin that will contain the code to inform Algolia who we are.

export default function (context, inject) {
    const appId = 'SZEW42EG32'
    const apiKey = '1cb012681351f6a27e7c0133a9f20021'

    inject('dataApi', {
        getHome
    })
    async function getHome(homeId) {
        const response = await fetch(`https://${appId}-dsn.algolia.net/1/indexes/homes/${homeId}`,{
            headers: {
                'X-Algolia-API-Key': apiKey,
                'X-Algolia-Application-Id': appId
            }
        })
        const data = await response.json()
        return data
    }
}
Enter fullscreen mode Exit fullscreen mode

Take note that we’re using the async/await syntactic sugar, thanks to Nuxt use webpack and babel behind the scene, to transform our code in a good old promise that is understood for older browsers.
Lastly we’re using the inject method to expose the getHome function to the rest of the app. We’re using a generic name for flexibility, so if you need to change over the course of the project from any other search provider, you can do it easily.

Include the plugin in the nuxt.config.js

nuxt.config.js

plugins:['~/plugins/dataApi.js']
Enter fullscreen mode Exit fullscreen mode

and then we can use it in our component, created lifecycle hook.

home.vue

    async created(){
        const home = await this.$dataApi.getHome(this.$route.params.id)
        this.home = home
    }
Enter fullscreen mode Exit fullscreen mode

Because Nuxt, doesn’t wait for that promise to resolve (async created), there is a method asyncData when it comes to works with API, only available in Nuxt. This method, receive is the context object similar to the plugin. It gets triggers on the Client side routing or in the server side when we hit it.

    async asyncData({params, $dataApi}){
        const home = await $dataApi.getHome(params.id)
        return {
            home
        }
    }
Enter fullscreen mode Exit fullscreen mode

I'll leave the apiKey open for a couple of weeks, so you can easily try.

Take care and enjoy your process.

Top comments (0)