Step 1: Install the Required Packages
First, ensure you have Node.js installed. Then, install the required npm packages:
npm install shopify-api-node dotenv
Step 2: Set Up Your .env
File
Create a .env
file in the root of your project. This file will store your Shopify API credentials securely:
SHOPIFY_SHOP_NAME=your-shop-name
SHOPIFY_API_KEY=your-api-key
SHOPIFY_PASSWORD=your-password
Step 3: Load Environment Variables with dotenv
Modify your Node.js application to load environment variables from the .env
file using dotenv
. Create a file, index.js
, or modify your existing entry file:
require('dotenv').config()
const Shopify = require('shopify-api-node')
const shopify = new Shopify({
shopName: process.env.SHOPIFY_SHOP_NAME,
apiKey: process.env.SHOPIFY_API_KEY,
password: process.env.SHOPIFY_PASSWORD
})
async function createProduct() {
const newProduct = {
title: 'New Product Title',
body_html: '<strong>Good product!</strong>',
vendor: 'Your Vendor Name',
product_type: 'Your Product Type',
tags: ['tag1', 'tag2'],
variants: [
{
option1: 'Default Title',
price: '19.99',
sku: '123',
inventory_quantity: 100
}
],
images: [
{
src: 'https://example.com/path/to/image.jpg'
}
]
}
try {
const createdProduct = await shopify.product.create(newProduct)
console.log(`Product created: ${createdProduct.id}`)
} catch (error) {
console.error(`Failed to create product: ${error.message}`)
}
}
createProduct()
Step 4: Add .env
to .gitignore
To ensure that your API credentials are not exposed, add your .env
file to .gitignore
:
echo .env >> .gitignore
Step 5: Test Your Setup
Run your Node.js application to ensure that everything is working correctly:
node index.js
Summary of Key Steps:
- Install Dependencies: Install
shopify-api-node
anddotenv
. - Set Up Environment Variables: Store your Shopify API credentials in a
.env
file. - Load Environment Variables: Use
dotenv
to load these credentials into your application. - Use Shopify API: Utilize the
shopify-api-node
package to interact with Shopify’s API. - Secure Credentials: Ensure the
.env
file is added to.gitignore
to prevent credentials from being exposed in your version control system.
By following these steps, you can securely manage your Shopify API credentials in a Node.js application, ensuring that sensitive information is protected.
Leave a Reply