Codementor Events

How to Build a Personal Music Site powered by Cosmic JS and Nuxt.js

Published Aug 10, 2018Last updated Feb 06, 2019
How to Build a Personal Music Site powered by Cosmic JS and Nuxt.js

Cosmic JS allows you to easily create nested Object structures and upload media files. In this tutorial we will learn how nested structures are built and how you can fetch this data from the Cosmic JS API to use in a simple, personal music website powered by Cosmic JS and Nuxt.js.

TL;DR:

Personal Music Site Demo
Personal Music Site Codebase

Intro

As there are already numerous articles where you can learn how to work with the Cosmic JS Dashboard, we will use an already prepared Bucket snapshot.

Create a Bucket

At first, you will need to create a fresh Bucket as the next step will remove all data from it.

Download base bucket.json which contain Bucket Objects template description as well as some demo data for our app. To import it to your Bucket simply follow your Bucket dashboard page and navigate to Settings > Import / Export section; you will see the Add import file button — click it and select bucket.json file you downloaded before.

Now your Bucket with freshly imported Object templates allow you to build Objects into next structures:
0*MGiZeduShO51JYc3.png

In Cosmic JS when you need to nest/link Objects into another Object you use the Multiple Objects Relationship metafield. Then, when you fetch the root Object you will get all items related to it by Metafield objects. In next paragraph you will see how to deploy an app that accesses such structures with just one Cosmic JS API request.

Deploy the application

To deploy an actual app follow next steps:

1) Clone the repository to your machine and go to freshly created folder

git clone https://github.com/zezic/cosmicjs-music-site.git
cd cosmicjs-music-site

2) Install app dependencies

npm install

3) Configure your local app instance

Actually, the way Cosmic JS hosted apps are configured is by reading environment variables, but this time to be more clear with our local deployment we just edit file called instance.config.js. To be able to run the app against your own Cosmic JS Bucket you will need to change next 3 attributes in this file:

  • slug
  • read_key
  • write_key

To obtain this settings go to your Bucket dashboard and navigate to Settings > Basic Settings. There you will see fields called:

  • Bucket slug
  • API Read Access Key
  • API Write Access Key

Copy values from those fields to your instance.config.js and save it. After that it should look like that:

module.exports = {
  keyColorBG: '#5339F1',
  keyColorFG: '#FFFFFF',
  secondColorBG: '#1A1A1A',
  secondColorFG: '#FFFFFF',
  loadingColor: '#FFCC00',
  slug: 'my-own-music-site',
  read_key: 'JAS2t6VWeawyalfAZluKpU70c0nbHRpNz1GYUx0lZUYdPYA8Ln',
  write_key: 'IFtzAiMVDOPvXIpyt11k7MFW19u2fehFzlGFz4cJHirpbAe1uD'
}

4) Run the app

npm run start

After the app builds you will see the message saying that the server is started at its address and port. Navigate to this address with your web browser. You should see the app homepage with demo data loaded from your Bucket:
0*zlM1uIwiyE7dh459.png

Learn how data is fetched

Fetching data from Cosmic JS to your JS app is pretty simple when you get used to JavaScript as an asynchronous language itself. In this particular app example we use a small factory that produces a promise which later resolves to the Bucket instance that allows us to fetch Objects from it. In this file you can see how it’s done:


import Cosmic from 'cosmicjs'
const cosmic = Cosmic()

const config = {
  slug: process.env.slug,
  read_key: process.env.read_key,
  write_key: process.env.write_key
}

export default function getBucket () {
  return cosmic.bucket(config)
}

You can notice how Bucket initialization requires parameters that we set up prior in the configuration file.

Then you can see how Bucket access is actually used in the app’s state management. Here is the simplified view of index Vuex file:


import getBucket from '~/lib/cosmic'

export const state = () => ({
  author: null
})

export const mutations = {
  setAuthor (state, author) {
    state.author = author
  }
}

export const actions = {
  async nuxtServerInit ({ commit }) {
    const bucket = await getBucket()
    const response = await bucket.getObjects({
      type: 'authors',
      limit: 1,
      hide_metafields: true
    })
    if (response.status !== 'empty') {
      const author = response.objects[0]
      commit('setAuthor', author)
    }
  }
}

Here we awaiting when promise with Bucket resolves. Then we call getObjects with type of ‘authors’, quantity limited to 1 and disabled metafields explanation. Then if the response is returned with non empty status, we pick the first-received Object and store it to our state. That’s it!

If you want to look at received data more closely, you can install vue-devtools, then run app in development mode by “npm run dev” command and inspect Vuex state via vue-devtools in your browser. You will see that received data tree contains not only Author object, but also related Albums and Tracks.

What about pushing data to Cosmic JS?

You also can not only “read” Objects from your Bucket, but also write (create) them into it. To involve this type of operation our app allows users to post Comments regarding Albums. Look at next piece of code in the context of comment form and you will see that creating Objects with addObject method is as simple as getting them by getObjects from Cosmic JS.

Conclusion

Cosmic JS allows you to create data structures based on Multiple Objects Relationships and then receive this data in your app by few lines of code.

If you have any comments or questions about building apps with Cosmic JS, reach out to us on Twitter and join the conversation on Slack.

Discover and read more posts from Carson Gibbons
get started