Set Up Local Environment Variables
-
Create a
.env.local
file in the root of your Next.js project to store your Shopify API credentials:
SHOPIFY_STORE_DOMAIN=your-shopify-store.myshopify.com SHOPIFY_STOREFRONT_ACCESS_TOKEN=your-storefront-access-token
Replace
your-shopify-store.myshopify.com
with your Shopify store URL, andyour-storefront-access-token
with the Storefront API token.
Create lib
Folder for the Fetching.
- Create a
lib
folder in the root directory of your project. - Inside the
lib
folder, create a new file calledstore.js
. -
Add the following code to
store.js
:
// lib/shopify.js export async function getStoreDetails() { const query = ` { shop { name primaryDomain { url } paymentSettings { currencyCode } } } `; try { const response = await fetch(`https://${process.env.SHOPIFY_STORE_DOMAIN}/api/2024-04/graphql`, { method: "POST", headers: { "Content-Type": "application/json", "X-Shopify-Storefront-Access-Token": process.env.SHOPIFY_STOREFRONT_ACCESS_TOKEN, }, body: JSON.stringify({ query }), }); const json = await response.json(); if (json.errors) { console.error("GraphQL errors:", json.errors); return null; // Return null if there's an error } return json.data.shop; // Return shop data } catch (error) { console.error("Error fetching store details:", error); return null; // Handle fetch errors } }
Displaying Store Details
- Go to the
app/pages.js
file. -
Add the following code to fetch and display the store details:
// app/page.js import { getStoreDetails } from '../lib/store'; export default async function StoreDetailsPage() { // Fetch store details const storeDetails = await getStoreDetails(); // If data fetching failed, handle it here if (!storeDetails) { return <div>Error fetching store details.</div>; } return ( <> <main className="container mx-auto p-4"> <p className='text-xl mb-4'>This is the home page.</p> <div> <h1 className='text-3xl font-bold'>Store Details</h1> <p><strong>Name:</strong> {storeDetails.name}</p> <p><strong>URL:</strong> <a href={storeDetails.primaryDomain.url}>{storeDetails.primaryDomain.url}</a></p> <p><strong>Currency:</strong> {storeDetails.paymentSettings.currencyCode}</p> </div> </main> </> ); }
That’s it! Your store details will now be displayed on the main page.
Output like this:
This is the home page.
Store Details
Name: my-store
URL: https://my-store.myshopify.com/
Currency: INR
Top comments (0)