How to Create a Shopify Application Using Next.js and Prisma, Along wi – Webinopoly ””

Let’s Discuss Your Project

Tell us a bit more about what you are working on, and let’s connect.

By entering your number, you agree to receive mobile messages at the phone number provided.* We do NOT sell or share your personal information.

Request a Quote
 

How to Create a Shopify Application Using Next.js and Prisma, Along with the Snippets VSCode Extension: A Step-by-Step Guide.

TABLE OF CONTENTS:

Shopify App Template | Next.js | Typescript

Key Features:

Shopify App Template for Node

Deployment

Advantages:

Tech Stack:

Hosting

NPM Scripts:

Creating Extensions

APIs

Webhooks

Next.js

Setup WIP

NPM Scripts:

Shopify serves as a comprehensive e-commerce platform, empowering businesses to establish and oversee online stores effortlessly. It furnishes an array of functionalities and tools tailored for product sales, inventory management, payment processing, and the seamless customization of online store designs.

With the knowledge of Shopify comes the Shopify Next.js Starter, which represents a foundational template or boilerplate designed specifically for constructing Shopify storefronts through the utilization of Next.js. Next.js stands out as a widely acclaimed React framework, renowned for its proficiency in crafting dynamic web applications. The Shopify Next.js Starter goes beyond mere provision, delivering a pre-configured setup that streamlines the integration of a Next.js frontend with the Shopify platform. This not only expedites the development process but also equips developers with the means to commence the creation of bespoke Shopify storefronts, leveraging the latest advancements in web technologies.

Shopify App Template | Next.js | Typescript

This predefined starter template for embedded Shopify apps comes with a strong recommendation to use Typescript throughout the entire development process.

Key Features:

  • 📝 TypeScript: Emphasizes the use of TypeScript for enhanced type safety and code clarity.⚡ Next.js: Leverages Next.js, a React framework known for static rendering, 
  • provides a performant and scalable foundation for the app.
  •  Serverless Architecture: Utilizes middleware and Next.js APIs for OAuth, eliminating the need for a custom server.
  • 💳 App Subscriptions: Incorporates functionality for managing app subscriptions.
  • 💾 Session Storage with Redis: Implements session storage using Redis, enhancing data persistence.
  • 🚇 Ngrok for Development:Streamlines development with Ngrok for easy testing and sharing of local environments.
  • 🪝 Webhook Registration and Persistence: Ensures webhook registration and persistence even after server restarts.
  • 🔑 Online and Offline Access Tokens: ready-to-use online and offline access tokens that can be used simultaneously.
  • 🌐 App Context Setup: Establishes an app context for storing data needed in multiple places, optimizing data fetching.
  • Request Verification Setup: Implements a robust system for verifying incoming requests.
  • Link Component: Provides a Link component to convert <a> tags to Next Links, facilitating the use of relative paths.
  • Route Propagation Setup: Configures route propagation for seamless navigation.
  • Examples for App Subscriptions: This includes examples for creating and displaying app subscriptions.
  • Loading Screen: Displays a loading screen while the app context is initializing, enhancing user experience during app startup.

Note: This template is opinionated in its approach, emphasizing the exclusive use of TypeScript for a consistent and robust development experience.

Shopify App Template for Node

This serves as a framework for constructing a Shopify app utilizing Node and React. It encompasses fundamental elements essential for Shopify app development.

Rather than duplicating this repository, employ your preferred package manager alongside the Shopify CLI, following these steps.

Getting Started

Requirements:

  • Ensure you have Node.js installed; if not, download and install it.
  • Create a Shopify partner account if you don't have one.
  • Set up a store for testing, either a development store or a Shopify Plus sandbox store.

Installing the template:

This template is installable using your preferred package manager.

Using yarn:

bash

yarn create @shopify/app --template=node

Using npm:

npm init @shopify/app@latest -- --template=node


Using pnpm:

bash

pnpm create @shopify/app@latest --template=node

This command clones the

template and installs the necessary dependencies.

Local Development:

The Shopify CLI connects to an app in your partner dashboard, providing environment variables, parallel command execution, and updated application URLs for easier development.

Develop locally using your preferred package manager. Run one of the following commands from the root of your app:

Using yarn:

yarn dev

Using npm:

npm run dev

Using pnpm:

pnpm run dev

Open the URL generated in your console. After granting permission to the app, you can commence development.

Deployment

Application Storage:

This template utilizes SQLite for session data storage. The database, named database. sqlite, is automatically created in the root. This SQLite usage is production-ready for single-instance app runs.

Choose a database based on your app's data needs and querying methods. Run your chosen database on your server or host it with a SaaS company. Here are some database providers with free tiers to get started:

Database

Type

Hosters

MySQL

SQL

Digital Ocean, Planet-Scale, Amazon Aurora, and Google Cloud SQL

PostgreSQL

SQL

Digital Ocean, Amazon Aurora, and Google Cloud SQL

Redis

Key-value

Digital Ocean, Amazon MemoryDB

MongoDB

NoSQL or Document

Digital Ocean, MongoDB Atlas

To switch to another database, modify your session storage configuration. Refer to a list of SessionStorage adapter packages for assistance.

Build:

The front end is a single-page app requiring the SHOPIFY_API_KEY, found on your app's page in your Partners dashboard. Paste your app’s key in the command for your preferred package manager:

Using yarn:

cd web/frontend/ && SHOPIFY_API_KEY=REPLACE_ME yarn build

Using npm:

cd web/frontend/ && SHOPIFY_API_KEY=REPLACE_ME npm run build

Using pnpm:

cd web/frontend/ && SHOPIFY_API_KEY=REPLACE_ME pnpm run build

There is no need to build the backend. Repeat the process for the following sections, maintaining the same format.

Advantages:

Shopify apps leverage various Shopify tools for an optimal merchant experience. The tutorial in our developer documentation outlines the process of building a Shopify app using this template.

The Node app template incorporates the following pre-configured features:

OAuth: Facilitating app installation and permission grants.

GraphQL Admin API: Facilitating querying or mutation of Shopify admin data.

REST Admin API: Resource classes for seamless interaction with the API.

Shopify-specific tooling:

  • AppBridge
  • Polaris
  • Webhooks

Tech Stack:

This template amalgamates several third-party open-source tools:

Express: Constructs the backend.

Vite: Constructs the React frontend.

React Router: Implemented for routing, with an additional layer of file-based routing.

React Query: Utilized for querying the admin API.

  • i18next and related libraries: Employed for frontend internationalization.
  • react-i18next: Facilitates react-specific i18n functionality.
  • i18next-resources-to-backend: Dynamically loads app translations.
  • @formatjs/intl-locale-matcher: Matches user locales with supported app locales.
  • @formatjs/intl-locale: Acts as a polyfill for Intl.  Locale if necessary.
  • @formatjs/intl-plural rules: Acts as a polyfill for Intl.  Plural rules, if necessary.

The following Shopify tools complement these third-party tools, streamlining the app development process:

Shopify API library: Adds OAuth to the Express backend, enabling users to install the app and grant scope permissions.

App Bridge React: Adds authentication to API requests in the front end and renders components outside of the app’s iFrame.

Polaris React: A robust design system and component library aiding developers in creating high-quality, consistent experiences for Shopify merchants.

Custom hooks: Enable authenticated requests to the Admin API.

File-based routing simplifies the creation of new pages.

@shopify/i18next-shopify: A plugin for i18next that aligns translation files with the JSON schema used by Shopify app extensions and themes.

Hosting

When you're prepared to deploy your app in a production environment, refer to our deployment documentation for guidance on hosting your app on cloud providers such as Heroku or Fly.io.

During the setup of environment variables, ensure to set the variable NODE_ENV=production.

Known Issues

Hot Module Replacement and Firefox

If, when running the app in development mode on Firefox, you encounter constant reloading, follow these steps to resolve the issue. These adjustments apply to your app's web/frontend/vite.config.js file after updating the CLI to v3.4.0:

Change the definition of the hmrConfig object to:

javascript

const host = process.env.HOST

  ? process.env.HOST.replace(/https?:\/\//, "")

  : "localhost";


let hmrConfig;

if (host === "localhost") {

  hmrConfig = {

    protocol: "ws",

    host: "localhost",

    port: 64999,

    clientPort: 64999,

  };

} else {

  hmrConfig = {

    protocol: "wss",

    host: host,

    port: process.env.FRONTEND_PORT,

    clientPort: 443,

  };

}


Change the server.host setting in the configs to "localhost":

javascript

server: {

  host: "localhost",

  // ...

}


Can't Get Past the ngrok "Visit Site" Page

If you encounter the ngrok interstitial page with a warning while previewing your app or extension and clicking "Visit Site" doesn't progress, follow these steps. Run dev using an alternate tunnel URL via tunneling software. The Cloudflare Tunnel has been validated to work with this template.

Install the Cloudflare CLI tool and run:


#Note: You can use a different port

cloudflared tunnel --url http://localhost:3000


From the logs, identify the https URL ending with trycloudflare.com. This is your tunnel URL. Replace the randomly generated hostname with your copied URL and, in a different terminal window, navigate to your app's root:

Using yarn:

bash

yarn dev --tunnel-url https://randomly-generated-hostname.trycloudflare.com:3000


Using npm:

bash

npm run dev --tunnel-url https://randomly-generated-hostname.trycloudflare.com:3000


Using pnpm:

bash

pnpm dev --tunnel-url https://randomly-generated-hostname.trycloudflare.com:3000


Repeat the process for the following sections, maintaining the same format.


In-Depth Guide: Setting Up and Customizing the Repo

  1. Run npm run g:install to install global dependencies.
  • This step, while not required every time, is essential for local development. It installs the Shopify/app and Shopify/cli packages. Refer to package.json for more details.
  1. Run npm i --force to install dependencies.
  • Ensures the use of the latest package versions. If any compatibility issues arise during installation, there should be no adverse effects on functionality. Do not delete the shopify.app.toml file, as it is required for the proper functioning of Shopify CLI 3.0, even if the file is empty.
  1. Create a new app (public or custom) from your Shopify Partner Dashboard.
  • The app URL will be generated later in the setup. Add https://localhost for now.
  1. Build your .env file based on .env.example.
  • Configure the following parameters:
  • SHOPIFY_API_KEY: App API key.
  • SHOPIFY_API_SECRET: App secret.
  • SHOPIFY_API_SCOPES: Scopes required by your Shopify app. Refer to access scopes.
  • SHOPIFY_APP_URL: URL generated from Ngrok.
  • SHOPIFY_API_VERSION: Pre-filled to the latest version.
  • DATABASE_URL: Database connection URL (supports SQL and noSQL databases using Prisma ORM).
  • ENCRYPTION_STRING: A string for encryption of the session token. Must be kept securely.

NPM Scripts:

  • dev: Run in dev mode.
  • build: build for production.
  • start: Start in production mode (requires npm run build before starting).
  • pretty: Run prettier on the entire project.
  • update: Force updates all packages to the latest version (requires manual npm i --force after).
  • update:url: Use @shopify/cli-kit to update URLs to your Shopify partner dashboard (requires proper setup of .env file).
  • ngrok:auth: Replace <auth-token-goes-here> with your ngrok token and run to activate ngrok.
  • ngrok: Starts ngrok on port 3000.
  • g:install: Required global installs for building Shopify apps.
  • Shopify: Allows access to Shopify CLI commands.
  • s:e:create: Create a Shopify extension.
  • s:e:deploy: Deploy extension to Shopify.
  • pg:create: Create a new folder database and initialize a PostgreSQL instance (requires Postgres installed).
    • Run brew install postgresql.
  • pg:start: Start a PostgreSQL instance on the database (requires npm run pg:create before this).
  • pg:stop: Stop PostgreSQL server.
  • prisma: Generic command to access prisma commands.
  • prisma:push: Push schema.prisma to your DATABASE_URL database.
  • prisma:pull: Pull database schema from DATABASE_URL database and generate a schema.prisma file.
  • prepare: reserved script to generate @prisma/client.

Setup Partner Dashboard:

  • Run npm run ngrok to generate your subdomain. Copy the https://<your-url> domain and add it to SHOPIFY_APP_URL in your .env file.
  • Run npm run update:url or manually update in Shopify Partner Dashboard > Apps > Your App Name > App Setup.

In the URLs section:

  • App URL: https://<your-url>
  • Allowed Redirection URL(s):
  • https://<your-url>/api/auth/callback
  • https://<your-url>/api/auth/tokens
  • Ensure consistency between the URL in your .env and app setup to avoid "URI not whitelisted" issues.

GDPR handlers are available at page/api/gdpr/ with registration URLs:

Customers Data Request: https://<your-url>/api/gdpr/customers_data_request

Customers Redact: https://<your-url>/api/gdpr/customers_redact

Shop Redact: https://<your-url>/api/gdpr/shop_redact

App proxy routes are set up to access data from your app directly from the store. Example proxy route: /pages/api/proxy_route.

Set up base URLs:

Subpath Prefix: apps

Subpath: next-proxy

Proxy URL: https://<your-url>/api/proxy_route

Confirm setup by visiting https://shop-url.com/apps/next-proxy/json and getting a JSON response.

Note: Avoid 404 errors by changing the subpath to something unique for each app installation.

Running the app:

  • If you are connecting to the database for the first time, run npx prisma db push.
  • Run npm run dev, your database, and ngrok.
  • Install the app by visiting https://ngrokurl.io/api/auth?shop=maystorename.myshopify.com.

Repeat the process for the following sections, maintaining the same format.

Creating Extensions

When generating extensions, avoid running the extension generator directly in this folder. Instead, follow these steps to minimize dependency clashes:

If not done already, execute npm run g:install. This globally installs the @shopify/app and @shopify/cli packages.

Adjust the folder structure.

  • Before: nextjs-app/
  • After: app-name/ app-name/extensions app-name/nextjs-app

This restructuring ensures that extensions have their own package.json and do not encounter issues with other dependencies in the Next.js app.

In app-name/extensions, run npm init --y and add the following scripts to your package.json:

json

"scripts": {

  "shopify": "shopify",

  "generate": "shopify app generate extension",

  "dev": "shopify app dev",

  "build": "shopify app build",

  "info": "shopify app info",

  "deploy": "shopify app deploy"

}

Now you're all set to create extensions! When deploying to Vercel, make sure to adjust settings to point to app-name/nextjs-app for build and deployment.

APIs

All APIs must incorporate middlewares. For App Proxy, it's export default withMiddleware("verifyProxy")(handler), and for Apps route (the regular backend), it's export default withMiddleware("verifyRequest")(handler)

Example implementations can be found in pages/api/proxy_route/json.js and pages/api/apps/index.js. If middlewares aren't used, your app could be rejected, and running APIs without context poses a security risk.

Webhooks

The process of handling webhooks has undergone some changes, especially for those transitioning from Mongo. To add your webhooks:

  1. 1. Navigate to utils/shopify.js.
  2. 2. At the bottom, add all your webhooks and handlers.

It's advisable to delegate webhook handling (excluding APP_UNINSTALLED) to a separate service such as Google PubSub, AWS EventBridge, or Cloudflare Workers. This ensures scalability, allowing you to manage large volumes of webhooks during peak times like Black Friday.

Next.js

If unsure about what gets shipped to the browser, explore the Next.js Code Elimination Tool.

Setup WIP

This comprehensive guide walks you through the process of setting up and using this repository. It covers everything from getting the base repository up and running to understanding how to add your own customizations on the server side, such as registering webhooks and routes. For additional details, refer to the Notes section.

  1. 1. Run npm run g:install to install global dependencies.
  • This step is not required every time but is essential for local development when installing the Shopify/app and Shopify/cli packages. Refer to package.json for more information.
  1. 2. Run npm i --force to install dependencies.
  • Extensive efforts have been made to use the latest package versions. Incompatibility issues may arise during installation, but there are no negative effects on functionality. If you encounter any issues, please open an issue.
  • Even if the shopify.app.toml file is empty, don't delete it because Shopify CLI 3.0 needs it to work properly.
  1. 3. Create a new app (public or custom) from your Shopify Partner Dashboard.
  • The app URL will be generated later in the setup. Add https://localhost for now.
  1. 4. Build your .env file based on .env.example.
  • SHOPIFY_API_KEY: App API key.
  • SHOPIFY_API_SECRET: App secret.
  • SHOPIFY_API_SCOPES: Scopes required by your Shopify app. Access scopes can be found here.
  • SHOPIFY_APP_URL: URL generated from Ngrok.
  • SHOPIFY_API_VERSION: Pre-filled to the latest version. All calls in the repo are based on this API version. If you're downgrading, refer to the official documents. The repo is kept up-to-date with the newest practices.
  • DATABASE_URL: Database connection URL. Prisma ORM is used, supporting both SQL and NoSQL databases. Read more about it here.
  • ENCRYPTION_STRING: A string for encryption to encrypt session tokens. some random salt and save it. Losing the string means you cannot decrypt your sessions, so keep it safe.

NPM Scripts:

  • dev: Run in dev mode.
  • build: build for production.
  • start: Start in production mode. It requires npm run build before starting.
  • pretty: Run prettier on the entire project.
  • update: Force updates all packages to the latest version and requires manual npm i --force after. It's not recommended if you don't know what you're doing.
  • update:url: Use @shopify/cli-kit to update URLs on your Shopify partner dashboard. It requires a proper setup of .env file.
  • ngrok:auth: Replace <auth-token-goes-here> with your Ngrok token and run it to activate Ngrok.
  • ngrok: Starts Ngrok on port 3000.
  • g:install: Required global installs for building Shopify apps.
  • shopify: Allows you to access Shopify CLI commands. Try npm run Shopify Help for more info.
  • s:e:create: Create a Shopify extension.
  • s:e:deploy: Deploy extension to Shopify.
  • pg:create: Create a new folder database and initialize a PostgreSQL instance. It requires you to have PostgreSQL installed.
  • Run brew install postgresql.
  • pg:start: Start a PostgreSQL instance on the database. It requires you to run npm run pg:create before you can do this.
  • pg:stop: Stop PostgreSQL server.
  • prisma: Generic command to access 
  • Prisma commands.
  • prisma:push: Push schema.prisma to your DATABASE_URL database.
  • prisma:pull: Pull the database schema from the DATABASE_URL database and generate a schema.prisma file.
  • prepare: reserved script to generate @prisma/client.

Setup Partner Dashboard:

  • Run npm run ngrok to generate your subdomain. Copy the https://<your-url> domain and add it to SHOPIFY_APP_URL in your .env file.
  • Run npm run update:url, or manually go to Shopify Partner Dashboard > Apps > Your App Name > App Setup.
  • In the URLs section:
  • App URL: https://<your-url>
  • Allowed Redirection URL(s):
  • https://<your-url>/api/auth/callback
  • https://<your-url>/api/auth/tokens
  • Ensure the same URL is used in your .env and App Setup sections to avoid "URI not whitelisted" issues.
  • GDPR handlers are available at page/api/gdpr/ with the following URLs to register:

Customer Data Request: -https://<your-url>/api/gdpr/customers_data_request

-Customers Redact: https://<your-url>/api/gdpr/customers_redact

-Shop Redact: https://<your-url>/api/gdpr/shop_redact

-App Proxy routes are set up to allow access to data from your app directly from the store. An example proxy route is available at /pages/api/proxy_route. To set it up:

  • Subpath Prefix: apps
  • Subpath: next-proxy

-Proxy URL: https://<your-url>/api/proxy_route

Confirm proper setup by visiting https://shop-url.myshopify.com/apps/next-proxy/json to check if you receive a JSON response.

Running App:

  1. If it's your first time connecting to the database, run npx prisma db push to get your database working.
  2. Run npm run dev, your database, and Ngrok.
  3. Install the app by visiting https://ngrokurl.io/api/auth?shop=mystorename.myshopify.com.

Bottom Line
In this extensive guide, we've walked through the step-by-step process of developing a Shopify application using the potent combination of Next.js and Prisma, as well as the productivity-enhancing Snippets VSCode extension. By leveraging Next.js, a React framework for web applications, and Prisma, a modern database toolkit, developers can build robust and scalable Shopify storefronts.

The integration of the Snippets VSCode extension adds an extra layer of convenience, enabling quick and efficient generation of boilerplate code and snippets for common tasks. This not only accelerates development but also ensures consistency across the codebase.

By following this guide, developers have gained insights into setting up the development environment, handling dependencies, and implementing crucial features such as OAuth, GraphQL integration, and app subscriptions. The use of Prisma for database management adds a layer of sophistication, while the snippets provided streamline the creation of various components and functionalities.

Ultimately, this guide equips developers with the tools and knowledge needed to embark on the creation of a customized Shopify application, combining modern web technologies and best practices for a seamless and feature-rich e-commerce experience.

Contact Us

Access unparalleled support with Webinopoly! Our comprehensive service hub is dedicated to addressing all your questions and issues, featuring a team of skilled professionals available around the clock. Whether you require assistance in website development, digital marketing, or any facet of your online business, we stand ready to support you. Rely on us for tailored, high-quality service at every juncture. Together, let's propel your business to new heights!

Share  

Let’s Discuss Your Project

Guides