4 Steps to Update the Next.js Marketplace Template
We recently updated the Next.js Marketplace template to the new Cosmic JavaScript SDK and I have to say, the process was quite quick and simple. The new SDK is much lighter in bundle size (by 93%) and provides a more declarative syntax including TypeScript support, making it the recommended way to connect your JavaScript apps to Cosmic.
The following article shows you the steps that were taken to make the upgrade and what to expect when you upgrade your projects to the new SDK.
Getting started
To get started, install the Next.js Marketplace template and view a live demo here.
The template includes common ecommerce marketplace functionality:
Browse, search, and filter products for sale.
Purchase a product using Stripe.
Create your own product for sale (requires Cosmic login).
Steps to Upgrade
The steps we took to upgrade this template are:
Installed the new Cosmic JavaScript SDK.
Updated the Bucket client configuration.
Added an additional parameter to fetch the products (
depth
).Simplified the logic to add products.
You can see the pull request where each of the updates were made. Let's go over each step:
1. Install the Cosmic JavaScript SDK
First, we removed the deprecated Cosmic NPM module:
pnpm remove cosmicjs
Then we installed the new Cosmic JavaScript SDK:
pnpm add @cosmicjs/sdk
2. Bucket configuration
Next, we updated the Bucket client configuration with the following code:
import { createBucketClient } from '@cosmicjs/sdk'
const cosmic = createBucketClient({
bucketSlug: process.env.NEXT_PUBLIC_COSMIC_BUCKET_SLUG,
readKey: process.env.NEXT_PUBLIC_COSMIC_READ_KEY,
writeKey: process.env.COSMIC_WRITE_KEY,
})
3. Object fetching
Then we added the depth
parameter to the part of the code that handles the product fetching. Note: This is now required when fetching nested Object relationship data.
In this example, to fetch the nested data from categories along with the product data, which is connected to the product model by a Multi-Object relationship Metafield, we set a depth of 1
.
const data = await cosmic.objects
.find({
type: 'products',
})
.props('title,slug,id,metadata.categories')
.depth(1)
See the PR update. For more information about Metafields, see Metafields in the docs.
4. Adding Objects
And lastly, we updated the way products are created as this has been dramatically simplified in the new API. Instead of a large metafields
array, you now have a concise metadata
object. (Less code FTW!)
Next steps
I hope you found this guide instructive. Sign up to get started using Cosmic to power content for your websites and apps.
If you are looking to migrate from the old dashboard, read the upgrade guide and reach out to Cosmic support if you need assistance.
Subscribe to my newsletter
Read articles from Tony Spiro directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by
Tony Spiro
Tony Spiro
Cosmic CEO and chief LFG officer.