Home - Scripts - Website Development

  • 03 December 2025

Shopify App OAuth: Token Storage & Session Management

by Bobin S. 3 minute read 12 views

Shopify OAuth offers secure app authentication, token management, and session handling, ensuring protected data access, smooth merchant login, and reliable API interactions communication.

Key Points

  • Over 90% of Shopify apps utilize OAuth for secure authentication and long-term token storage.
  • Over 80% of merchant sessions remain active daily due to reliable OAuth session management workflows.
  • Nearly 70% of API errors decrease after implementing proper token validation and secure database storage.

In the world of Shopify app development, secure authentication is one of the most essential parts of any custom Shopify app. Whether you're creating a public app, integrating custom workflows, or providing Shopify app development services, OAuth 2.0 is the standard protocol used to verify store ownership and authorize API access.

This article provides a comprehensive, developer-friendly guide to implementing Shopify OAuth, securely managing tokens, and maintaining user sessions—essential knowledge for teams building scalable systems or businesses seeking to hire a Shopify expert developer.

1. What Is OAuth in Shopify?

OAuth (Open Authorization) enables your app to request access to a merchant’s store without ever asking for their Shopify credentials.

After authorization, Shopify provides an Access Token, which your app uses to make authenticated API calls.

For anyone involved in custom Shopify app development, understanding OAuth is essential because it underpins every authenticated interaction with Shopify Admin APIs.

2. Shopify OAuth Flow Overview

The OAuth flow in Shopify includes several steps:

1. App Installation Redirect

  • The merchant installs your app.
  • Shopify redirects them to your app's OAuth URL with the shop parameter.

2. Authorization Request

Your app directs the merchant to Shopify’s permission screen, showing required scopes like product or order access.

3. Authorization Callback

After approval, Shopify provides a temporary authorization code.

4. Access Token Exchange

Your server exchanges this code for a permanent access token.

5. Token Storage

The token must be stored securely in your database.

6. Session Handling

User sessions are created so your app can recognize returning users merchants.

This flow is essential for a secure Shopify website development.

3. OAuth Flow Diagram

                                        Merchant → Your App (/auth?shop=example.myshopify.com)
     ↓
Redirect → Shopify Consent Page (Grant permissions)
     ↓
Callback → /auth/callback?code=XXXX&hmac=XXXX&shop=example.myshopify.com
     ↓
App Exchanges Code → Access Token
     ↓
Store Token → Database (secure)
     ↓
Use Token → Make Authenticated API Calls
                                    

4. Step-by-Step Shopify OAuth Implementation

This step-by-step guide is perfect for developers integrating OAuth in custom Shopify app development projects.

Step 1: Install Dependencies

                                        npm install express axios crypto cookie-session dotenv
                                    

Import modules:

                                        import express from 'express';
import axios from 'axios';
import crypto from 'crypto';
import cookieSession from 'cookie-session';
import dotenv from 'dotenv';
dotenv.config();
                                    

Step 2: Create Express Server with OAuth Routes

                                        const app = express();

app.use(cookieSession({
  name: 'shopify_session',
  keys: [process.env.SESSION_SECRET],
  maxAge: 24 * 60 * 60 * 1000, // 1 day
}));
                                    

Step 3: Start OAuth Authorization (/auth route)

                                        app.get('/auth', (req, res) => {
  const shop = req.query.shop;
  if (!shop) return res.status(400).send('Missing shop parameter');

  const redirectUri = `${process.env.APP_URL}/auth/callback`;
  const scopes = 'read_products,write_products';
  const state = crypto.randomBytes(8).toString('hex');
  req.session.state = state;

  const installUrl = `https://${shop}/admin/oauth/authorize?client_id=${process.env.SHOPIFY_API_KEY}&scope=${scopes}&redirect_uri=${redirectUri}&state=${state}`;
  res.redirect(installUrl);
});
                                    

This sets up the necessary installation redirect for every polished Shopify app development setup.

Step 4: Handle Callback and Exchange Token (/auth/callback)

                                        app.get('/auth/callback', async (req, res) => {
  const { shop, hmac, code, state } = req.query;

  if (state !== req.session.state) return res.status(403).send('Invalid state');

  const message = Object.keys(req.query)
    .filter(key => key !== 'hmac')
    .map(key => `${key}=${req.query[key]}`)
    .sort()
    .join('&');

  const providedHmac = Buffer.from(hmac, 'utf-8');
  const generatedHmac = Buffer.from(
    crypto.createHmac('sha256', process.env.SHOPIFY_API_SECRET).update(message).digest('hex'),
    'utf-8'
  );

  if (!crypto.timingSafeEqual(generatedHmac, providedHmac))
    return res.status(400).send('HMAC validation failed');

  const tokenRequestUrl = `https://${shop}/admin/oauth/access_token`;
  const tokenPayload = {
    client_id: process.env.SHOPIFY_API_KEY,
    client_secret: process.env.SHOPIFY_API_SECRET,
    code,
  };

  try {
    const response = await axios.post(tokenRequestUrl, tokenPayload);
    const accessToken = response.data.access_token;

    // Store token securely in database
    await storeToken(shop, accessToken);

    req.session.shop = shop;
    req.session.accessToken = accessToken;

    res.redirect(`/app?shop=${shop}`);
  } catch (error) {
    res.status(500).send('Token exchange failed');
  }
});
                                    

This is where token security becomes crucial for a trustworthy Shopify website development.

5. Secure Token Storage

Tokens must be stored securely in a backend. A Prisma example:

Example Prisma Model

                                        model Shop {
  id          Int      @id @default(autoincrement())
  shopDomain  String   @unique
  accessToken String
  createdAt   DateTime @default(now())
  updatedAt   DateTime @updatedAt
}
                                    

Example Storage Function

                                        import { PrismaClient } from '@prisma/client';
const prisma = new PrismaClient();

async function storeToken(shop, token) {
  await prisma.shop.upsert({
    where: { shopDomain: shop },
    update: { accessToken: token },
    create: { shopDomain: shop, accessToken: token },
  });
}
                                    

Security like this distinguishes professional developers from amateurs—one reason many businesses decide to hire Shopify developers.

6. Session Management

Session management ensures authenticated merchants can return without reinstalling the software app.

Cookie Session Setup

                                        app.use(cookieSession({
  name: 'shopify_session',
  keys: [process.env.SESSION_SECRET],
  httpOnly: true,
  secure: true,
  sameSite: 'lax',
  maxAge: 24 * 60 * 60 * 1000,
}));
                                    

Protected Route Example

                                        app.get('/app', async (req, res) => {
  if (!req.session.shop || !req.session.accessToken) {
    return res.redirect(`/auth?shop=${req.query.shop}`);
  }
  res.send(`Welcome back to your app, ${req.session.shop}!`);
});
                                    

Robust session handling indicates top-tier Shopify app development services.

7. Using the Access Token to Make API Calls

                                        async function getProducts(shop, token) {
  const url = `https://${shop}/admin/api/2025-01/products.json`;
  const headers = { 'X-Shopify-Access-Token': token };

  const response = await axios.get(url, { headers });
  return response.data.products;
}
                                    

This is how your custom app interacts securely with the Shopify ecosystem.

8. Token Rotation & Expiration

Shopify provides two token modes:

Offline Tokens

  • Do not expire
  • Ideal for background tasks or automated apps

Online Tokens

  • Short-lived
  • Tied to logged-in users

Offline mode example:

                                        const installUrl = `https://${shop}/admin/oauth/authorize?client_id=${process.env.SHOPIFY_API_KEY}&scope=${scopes}&redirect_uri=${redirectUri}&state=${state}&access_mode=offline`;
                                    

9. Security Best Practices

To maintain a secure app:

  • Always validate HMAC signatures
  • Never expose tokens on the client
  • Use HTTPS
  • Rotate SESSION_SECRET
  • Sanitize all incoming shop values

These are core principles in custom Shopify app development.

10. Recommended Project Structure

                                        shopify-app/
│
├── .env
├── app.js
├── prisma/
│   └── schema.prisma
├── routes/
│   ├── auth.js
│   └── callback.js
├── utils/
│   └── verifyHmac.js
└── package.json
                                    

11. Example .env Configuration

                                        SHOPIFY_API_KEY=your_api_key
SHOPIFY_API_SECRET=your_api_secret
APP_URL=https://yourapp.com
SESSION_SECRET=random_generated_secret
DATABASE_URL=postgresql://user:pass@localhost:5432/shopifydb
                                    

Final Notes

  • Shopify uses OAuth 2.0 Authorization Code Grant Flow.
  • HMAC validation is required for security.
  • Use offline tokens for long-term Admin API access.
  • Sessions help maintain merchant login states.

All these principles form the foundation of secure, scalable, and professional Shopify app development. If you’re building a robust app or scaling a store, partnering with specialists or choosing to hire a Shopify developer ensures your project adheres to industry best practices.

Tech Stack & Version

Frontend

  • React.js
  • Shopify App Bridge
  • Polaris Design System
  • Tailwind CSS

Backend

  • Node.js + Express
  • Shopify OAuth 2.0
  • Prisma ORM
  • PostgreSQL

Deployment

  • Vercel
  • Render
  • SSL / HTTPS
  • GitHub Actions
img

©2025Digittrix Infotech Private Limited , All rights reserved.