Repository: Shopify/shopify-app-template-remix Branch: main Commit: 94d67091ef36 Files: 49 Total size: 75.0 KB Directory structure: gitextract_66wgcdz4/ ├── .dockerignore ├── .editorconfig ├── .eslintignore ├── .eslintrc.cjs ├── .github/ │ ├── CODEOWNERS │ ├── CODE_OF_CONDUCT.md │ ├── CONTRIBUTING.md │ ├── ISSUE_TEMPLATE.md │ ├── PULL_REQUEST_TEMPLATE.md │ ├── dependabot.yml │ └── workflows/ │ ├── ci.yml │ ├── cla.yml │ ├── close-waiting-for-response-issues.yml │ ├── convert-to-js.yml │ └── remove-labels-on-activity.yml ├── .gitignore ├── .graphqlrc.ts ├── .npmrc ├── .prettierignore ├── .vscode/ │ ├── extensions.json │ └── mcp.json ├── CHANGELOG.md ├── Dockerfile ├── README.md ├── app/ │ ├── db.server.ts │ ├── entry.server.tsx │ ├── globals.d.ts │ ├── root.tsx │ ├── routes/ │ │ ├── _index/ │ │ │ ├── route.tsx │ │ │ └── styles.module.css │ │ ├── app._index.tsx │ │ ├── app.additional.tsx │ │ ├── app.tsx │ │ ├── auth.$.tsx │ │ ├── auth.login/ │ │ │ ├── error.server.tsx │ │ │ └── route.tsx │ │ ├── webhooks.app.scopes_update.tsx │ │ └── webhooks.app.uninstalled.tsx │ ├── routes.ts │ └── shopify.server.ts ├── env.d.ts ├── extensions/ │ └── .gitkeep ├── package.json ├── prisma/ │ ├── migrations/ │ │ └── 20240530213853_create_session_table/ │ │ └── migration.sql │ └── schema.prisma ├── shopify.app.toml ├── shopify.web.toml.liquid ├── tsconfig.json └── vite.config.ts ================================================ FILE CONTENTS ================================================ ================================================ FILE: .dockerignore ================================================ .cache build node_modules ================================================ FILE: .editorconfig ================================================ # editorconfig.org root = true [*] charset = utf-8 indent_size = 2 indent_style = space insert_final_newline = true trim_trailing_whitespace = true # Markdown syntax specifies that trailing whitespaces can be meaningful, # so let’s not trim those. e.g. 2 trailing spaces = linebreak (
) # See https://daringfireball.net/projects/markdown/syntax#p [*.md] trim_trailing_whitespace = false ================================================ FILE: .eslintignore ================================================ node_modules build public/build shopify-app-remix */*.yml .shopify ================================================ FILE: .eslintrc.cjs ================================================ /** @type {import('@types/eslint').Linter.BaseConfig} */ module.exports = { root: true, extends: [ "@remix-run/eslint-config", "@remix-run/eslint-config/node", "@remix-run/eslint-config/jest-testing-library", "prettier", ], globals: { shopify: "readonly" }, }; ================================================ FILE: .github/CODEOWNERS ================================================ * @shop/dev_experience ================================================ FILE: .github/CODE_OF_CONDUCT.md ================================================ # Contributor Covenant Code of Conduct ## Our Pledge In the interest of fostering an open and welcoming environment, we as contributors and maintainers pledge to making participation in our project and our community a harassment-free experience for everyone, regardless of age, body size, disability, ethnicity, gender identity and expression, level of experience, nationality, personal appearance, race, religion, or sexual identity and orientation. ## Our Standards Examples of behavior that contributes to creating a positive environment include: - Using welcoming and inclusive language - Being respectful of differing viewpoints and experiences - Gracefully accepting constructive criticism - Focusing on what is best for the community - Showing empathy towards other community members Examples of unacceptable behavior by participants include: - The use of sexualized language or imagery and unwelcome sexual attention or advances - Trolling, insulting/derogatory comments, and personal or political attacks - Public or private harassment - Publishing others' private information, such as a physical or electronic address, without explicit permission - Other conduct which could reasonably be considered inappropriate in a professional setting ## Our Responsibilities Project maintainers are responsible for clarifying the standards of acceptable behavior and are expected to take appropriate and fair corrective action in response to any instances of unacceptable behavior. Project maintainers have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct, or to ban temporarily or permanently any contributor for other behaviors that they deem inappropriate, threatening, offensive, or harmful. ## Scope This Code of Conduct applies both within project spaces and in public spaces when an individual is representing the project or its community. Examples of representing a project or community include using an official project e-mail address, posting via an official social media account, or acting as an appointed representative at an online or offline event. Representation of a project may be further defined and clarified by project maintainers. ## Enforcement Instances of abusive, harassing, or otherwise unacceptable behavior may be reported by contacting the project team at opensource@shopify.com. All complaints will be reviewed and investigated and will result in a response that is deemed necessary and appropriate to the circumstances. The project team is obligated to maintain confidentiality with regard to the reporter of an incident. Further details of specific enforcement policies may be posted separately. Project maintainers who do not follow or enforce the Code of Conduct in good faith may face temporary or permanent repercussions as determined by other members of the project's leadership. ## Attribution This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4, available at https://www.contributor-covenant.org/version/1/4/code-of-conduct/ [homepage]: https://www.contributor-covenant.org ================================================ FILE: .github/CONTRIBUTING.md ================================================ # How to contribute The Shopify Remix app template is an open source project. We want to make it as easy and transparent as possible to contribute. If we are missing anything or can make the process easier in any way, please let us know by [opening an issue](https://github.com/Shopify/shopify-app-template-remix/issues/new). ## Code of conduct We expect all participants to read our [code of conduct](https://github.com/Shopify/shopify-app-template-remix/.github/CODE_OF_CONDUCT.md) to understand which actions are and aren’t tolerated. ## Open development All work on the Shopify Remix app template happens directly on GitHub. Both team members and external contributors send pull requests which go through the same review process. ## Bugs ### Where to find known issues We track all of our issues in GitHub and [bugs](https://github.com/Shopify/shopify-app-template-remix/labels/Bug) are labeled accordingly. If you are planning to work on an issue, avoid ones which already have an assignee, where someone has commented within the last two weeks they are working on it, or the issue is labeled with [fix in progress](https://github.com/Shopify/shopify-app-template-remix/labels/fix%20in%20progress). We will do our best to communicate when an issue is being worked on internally. ### Reporting new issues To reduce duplicates, look through open issues before filing one. When [opening an issue](https://github.com/Shopify/shopify-app-template-remix/issues/new?template=ISSUE.md), complete as much of the template as possible. ## Your first pull request Working on your first pull request? You can learn how from this free video series: [How to Contribute to an Open Source Project on GitHub](https://egghead.io/series/how-to-contribute-to-an-open-source-project-on-github) To help you get familiar with our contribution process, we have a list of [good first issues](https://github.com/Shopify/shopify-app-template-remix/labels/good%20first%20issue) that contain bugs with limited scope. This is a great place to get started. If you decide to fix an issue, please check the comment thread in case somebody is already working on a fix. If nobody is working on it, leave a comment stating that you intend to work on it. If somebody claims an issue but doesn’t follow up for more than two weeks, it’s fine to take it over but still leave a comment stating that you intend to work on it. ### Sending a pull request We’ll review your pull request and either merge it, request changes to it, or close it with an explanation. We’ll do our best to provide updates and feedback throughout the process. ### Contributor License Agreement (CLA) Each contributor is required to [sign a CLA](https://cla.shopify.com/). This process is automated as part of your first pull request and is only required once. If any contributor has not signed or does not have an associated GitHub account, the CLA check will fail and the pull request is unable to be merged. ================================================ FILE: .github/ISSUE_TEMPLATE.md ================================================ --- name: '🐛 Bug Report' about: Something isn't working labels: 'Type: Bug 🐛' --- # Issue summary Before opening this issue, I have: - [ ] Upgraded to the latest version of the `@shopify` packages - Affected `@shopify/shopify-*` package and version: - Node version: - Operating system: - [ ] Set `{ logger: { level: LogSeverity.Debug } }` in my configuration - [ ] Found a reliable way to reproduce the problem that indicates it's a problem with the package - [ ] Looked for similar issues in this repository - [ ] Checked that this isn't an issue with a Shopify API - If it is, please create a post in the [Shopify community forums](https://community.shopify.com/c/partners-and-developers/ct-p/appdev) or report it to [Shopify Partner Support](https://help.shopify.com/en/support/partners/org-select) ## Expected behavior What do you think should happen? ## Actual behavior What actually happens? ## Steps to reproduce the problem 1. 1. 1. ## Debug logs ``` // Paste any relevant logs here ``` ================================================ FILE: .github/PULL_REQUEST_TEMPLATE.md ================================================ ### WHY are these changes introduced? Fixes #0000 ### WHAT is this pull request doing? ### Test this PR ```bash shopify app init --template=https://github.com/Shopify/shopify-app-template-remix# ``` ### Checklist - [ ] I have made changes to the `README.md` file and other related documentation, if applicable - [ ] I have added an entry to `CHANGELOG.md` - [ ] I'm aware I need to create a new release when this PR is merged ================================================ FILE: .github/dependabot.yml ================================================ version: 2 updates: - package-ecosystem: github-actions directory: "/" schedule: interval: weekly # Enable version updates for npm - package-ecosystem: 'npm' # Look for `package.json` and `lock` files in the `root` directory directory: '/' # Check the npm registry for updates every day (weekdays) schedule: interval: 'weekly' # Dependabot defaults to 5 open pull requests at a time open-pull-requests-limit: 100 # Cooldown is the number of days after a release to wait until opening a PR # This gives us more confidence changes can be merged because changes have been community tested. # See: https://github.blog/changelog/2025-07-01-dependabot-supports-configuration-of-a-minimum-package-age/ cooldown: default-days: 14 semver-major-days: 30 semver-minor-days: 14 semver-patch-days: 14 groups: # Group together PRs of dependant packages prisma: patterns: - 'prisma' - '@prisma/client' react: patterns: - 'react' - 'react-dom' - '@types/react' - '@types/react-dom' vite: patterns: - 'vite' - 'vite-tsconfig-paths' remix: patterns: - '@remix-run/dev' - '@remix-run/fs-routes' - '@remix-run/node' - '@remix-run/react' - '@remix-run/eslint-config' - '@remix-run/route-config' # Group all patch updates not accounted for in prior groups in a single PR. # This reduces the number of PRs to review and rebase. patch-updates: patterns: - "*" update-types: - "patch" ================================================ FILE: .github/workflows/ci.yml ================================================ on: [push, pull_request] name: CI jobs: CI: name: CI_Node_${{ matrix.version }} runs-on: ubuntu-latest strategy: matrix: version: [20.19.0, 22, 24] steps: - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2 - uses: actions/setup-node@a0853c24544627f65ddf259abe73b1d18a591444 # v5.0.0 with: node-version: ${{ matrix.version }} - name: Install run: yarn install ================================================ FILE: .github/workflows/cla.yml ================================================ name: Contributor License Agreement (CLA) on: pull_request_target: types: [opened, synchronize] issue_comment: types: [created] jobs: cla: runs-on: ubuntu-latest if: | (github.event.issue.pull_request && !github.event.issue.pull_request.merged_at && contains(github.event.comment.body, 'signed') ) || (github.event.pull_request && !github.event.pull_request.merged) steps: - uses: Shopify/shopify-cla-action@v1 with: github-token: ${{ secrets.GITHUB_TOKEN }} cla-token: ${{ secrets.CLA_TOKEN }} ================================================ FILE: .github/workflows/close-waiting-for-response-issues.yml ================================================ name: Close Waiting for Response Issues on: schedule: - cron: "30 1 * * *" workflow_dispatch: jobs: check-need-info: runs-on: ubuntu-latest steps: - name: close-issues uses: actions-cool/issues-helper@45d75b6cf72bf4f254be6230cb887ad002702491 # v3.6.3 with: actions: "close-issues" token: ${{ secrets.GITHUB_TOKEN }} labels: "Waiting for Response" inactive-day: 14 body: | We are closing this issue because we did not hear back regarding additional details we needed to resolve this issue. If the issue persists and you are able to provide the missing clarification we need, you can respond here or create a new issue. We appreciate your understanding as we try to manage our number of open issues. ================================================ FILE: .github/workflows/convert-to-js.yml ================================================ name: Create Javascript conversion PR on: push: branches: - main workflow_dispatch: jobs: convert-ts-files: runs-on: ubuntu-latest steps: - name: Checkout Repo uses: actions/checkout@ee0669bd1cc54295c223e0bb666b733df41de1c5 # v2.7.0 - name: Create lock file run: touch yarn.lock - name: Setup Node.js uses: actions/setup-node@a0853c24544627f65ddf259abe73b1d18a591444 # v5.0.0 with: node-version: 22.12.x cache: 'yarn' - name: Install dependencies run: yarn add -W --dev @shopify/eslint-plugin --ignore-engines - name: Create temporary tsconfig file run: | echo '{ "include": ["./app/**/*", "*.ts", "*.tsx", ".graphqlrc.ts"], "compilerOptions": { "strict": true, "removeComments": false, "skipLibCheck": true, "isolatedModules": true, "noEmitOnError": true, "jsx": "preserve", "module": "ES2022", "moduleResolution": "bundler", "target": "ES2022", "paths": { "~/*": ["./app/*"] } } }' > tsconfig.js.json - name: Transpile to Javascript run: yarn tsc -p tsconfig.js.json - name: Remove Typescript files run: | find app \( -name "*.ts" -o -name "*.tsx" \) -delete find . \( -name ".graphqlrc.ts" -o -name "tsconfig.js.json" -o -name "vite.config.ts" \) -delete - name: Run prettier run: yarn prettier -w "app/**/*.{js,jsx}" ".graphqlrc.js" "vite.config.js" - name: Run ESLint run: | yarn lint "app/**/*.{js,jsx}" ".graphqlrc.js" "vite.config.js" --fix --no-cache --ignore-pattern "\!.graphqlrc.js" --plugin @shopify/eslint-plugin --rule '{ "import/order": "error", "import/newline-after-import": "error", "padding-line-between-statements": ["error", { "blankLine": "always", "prev": ["const", "let", "var"], "next": "*"}, { "blankLine": "any", "prev": ["const", "let", "var"], "next": ["const", "let", "var"]} { "blankLine": "always", "prev": "*", "next": "return" }, { "blankLine": "always", "prev": "*", "next": "export" }, { "blankLine": "never", "prev": "export", "next": "export" }, { "blankLine": "always", "prev": "*", "next": "block-like" }, { "blankLine": "always", "prev": "block-like", "next": "*" } ]}' - name: Prepare files for git run: | git config user.name GitHub git config user.email noreply@github.com git fetch git restore --staged package.json git restore package.json - name: Stage changes to files run: | git add . git checkout -b temp_javascript_updates git commit -m "Convert template to Javascript" git checkout javascript git pull git checkout - git rebase -m -X theirs javascript git push -f origin temp_javascript_updates:javascript_updates - name: Create Javascript PR run: | gh pr view --json mergedAt -q ".mergedAt" javascript_updates | grep -E "^$" || \ gh pr create -B javascript -H javascript_updates --title 'Convert template to Javascript' --body 'This is an automated PR that converts the latest changes from Typescript to Javascript' env: GH_TOKEN: ${{ github.token }} ================================================ FILE: .github/workflows/remove-labels-on-activity.yml ================================================ name: Remove Waiting Labels on: issue_comment: types: [created] workflow_dispatch: jobs: remove-labels-on-activity: runs-on: ubuntu-latest steps: - uses: actions/checkout@ee0669bd1cc54295c223e0bb666b733df41de1c5 # v2.7.0 - uses: actions-ecosystem/action-remove-labels@2ce5d41b4b6aa8503e285553f75ed56e0a40bae0 # v1.2.0 if: contains(github.event.issue.labels.*.name, 'Waiting for Response') with: labels: | Waiting for Response ================================================ FILE: .gitignore ================================================ node_modules .DS_Store /.cache /build /app/build /public/build/ /public/_dev /app/public/build /prisma/dev.sqlite /prisma/dev.sqlite-journal database.sqlite .env .env.* package-lock.json yarn.lock pnpm-lock.yaml /extensions/*/dist # Ignore shopify files created during app dev .shopify/* .shopify.lock ================================================ FILE: .graphqlrc.ts ================================================ import fs from "fs"; import { ApiVersion } from "@shopify/shopify-api"; import { shopifyApiProject, ApiType } from "@shopify/api-codegen-preset"; import type { IGraphQLConfig } from "graphql-config"; function getConfig() { const config: IGraphQLConfig = { projects: { default: shopifyApiProject({ apiType: ApiType.Admin, apiVersion: ApiVersion.July25, documents: [ "./app/**/*.{js,ts,jsx,tsx}", "./app/.server/**/*.{js,ts,jsx,tsx}", ], outputDir: "./app/types", }), }, }; let extensions: string[] = []; try { extensions = fs.readdirSync("./extensions"); } catch { // ignore if no extensions } for (const entry of extensions) { const extensionPath = `./extensions/${entry}`; const schema = `${extensionPath}/schema.graphql`; if (!fs.existsSync(schema)) { continue; } config.projects[entry] = { schema, documents: [`${extensionPath}/**/*.graphql`], }; } return config; } const config = getConfig(); export default config; ================================================ FILE: .npmrc ================================================ engine-strict=true @shopify:registry=https://registry.npmjs.org ================================================ FILE: .prettierignore ================================================ package.json .shadowenv.d .vscode node_modules prisma public .shopify ================================================ FILE: .vscode/extensions.json ================================================ { "recommendations": [ "graphql.vscode-graphql", "shopify.polaris-for-vscode", ] } ================================================ FILE: .vscode/mcp.json ================================================ { "servers": { "shopify-dev-mcp": { "command": "npx", "args": ["-y", "@shopify/dev-mcp@latest"] } } } ================================================ FILE: CHANGELOG.md ================================================ # @shopify/shopify-app-template-remix ## 2025.12.11 - [#1201](https://github.com/Shopify/shopify-app-template-remix/pull/1201) Update `@shopify/shopify-app-remix` to v4.1.0 and `@shopify/shopify-app-session-storage-prisma` to v8.0.0, add refresh token fields (`refreshToken` and `refreshTokenExpires`) to Session model in Prisma schema, and adopt the `expiringOfflineAccessTokens` flag for enhanced security through token rotation. See [expiring vs non-expiring offline tokens](https://shopify.dev/docs/apps/build/authentication-authorization/access-tokens/offline-access-tokens#expiring-vs-non-expiring-offline-tokens) for more information. ## 2025.10.01 **Remix is now React Router.** As of [React Router v7](https://remix.run/blog/merging-remix-and-react-router), Remix and React Router have merged. For new projects, use the **[Shopify App Template - React Router](https://github.com/Shopify/shopify-app-template-react-router)** instead. To migrate your existing Remix app, follow the **[migration guide](https://github.com/Shopify/shopify-app-template-react-router/wiki/Upgrading-from-Remix)**. ## 2025.08.16 - [#52](https://github.com/Shopify/shopify-app-template-remix/pull/1153) Use `ApiVersion.July25` rather than `LATEST_API_VERSION` in `.graphqlrc`. ## 2025.07.07 - [#1103](https://github.com/Shopify/shopify-app-template-remix/pull/1086) Remove deprecated .npmrc config values ## 2025.06.12 - [#1075](https://github.com/Shopify/shopify-app-template-remix/pull/1075) Add Shopify MCP to [VSCode configs](https://code.visualstudio.com/docs/copilot/chat/mcp-servers#_enable-mcp-support-in-vs-code) ## 2025.06.12 -[#1082](https://github.com/Shopify/shopify-app-template-remix/pull/1082) Remove local Shopify CLI from the template. Developers should use the Shopify CLI [installed globally](https://shopify.dev/docs/api/shopify-cli#installation). ## 2025.03.18 -[#998](https://github.com/Shopify/shopify-app-template-remix/pull/998) Update to Vite 6 ## 2025.03.01 - [#982](https://github.com/Shopify/shopify-app-template-remix/pull/982) Add Shopify Dev Assistant extension to the VSCode extension recommendations ## 2025.01.31 - [#952](https://github.com/Shopify/shopify-app-template-remix/pull/952) Update to Shopify App API v2025-01 ## 2025.01.23 - [#923](https://github.com/Shopify/shopify-app-template-remix/pull/923) Update `@shopify/shopify-app-session-storage-prisma` to v6.0.0 ## 2025.01.8 - [#923](https://github.com/Shopify/shopify-app-template-remix/pull/923) Enable GraphQL autocomplete for Javascript ## 2024.12.19 - [#904](https://github.com/Shopify/shopify-app-template-remix/pull/904) bump `@shopify/app-bridge-react` to latest - ## 2024.12.18 - [875](https://github.com/Shopify/shopify-app-template-remix/pull/875) Add Scopes Update Webhook ## 2024.12.05 - [#910](https://github.com/Shopify/shopify-app-template-remix/pull/910) Install `openssl` in Docker image to fix Prisma (see [#25817](https://github.com/prisma/prisma/issues/25817#issuecomment-2538544254)) - [#907](https://github.com/Shopify/shopify-app-template-remix/pull/907) Move `@remix-run/fs-routes` to `dependencies` to fix Docker image build - [#899](https://github.com/Shopify/shopify-app-template-remix/pull/899) Disable v3_singleFetch flag - [#898](https://github.com/Shopify/shopify-app-template-remix/pull/898) Enable the `removeRest` future flag so new apps aren't tempted to use the REST Admin API. ## 2024.12.04 - [#891](https://github.com/Shopify/shopify-app-template-remix/pull/891) Enable remix future flags. ## 2024.11.26 - [888](https://github.com/Shopify/shopify-app-template-remix/pull/888) Update restResources version to 2024-10 ## 2024.11.06 - [881](https://github.com/Shopify/shopify-app-template-remix/pull/881) Update to the productCreate mutation to use the new ProductCreateInput type ## 2024.10.29 - [876](https://github.com/Shopify/shopify-app-template-remix/pull/876) Update shopify-app-remix to v3.4.0 and shopify-app-session-storage-prisma to v5.1.5 ## 2024.10.02 - [863](https://github.com/Shopify/shopify-app-template-remix/pull/863) Update to Shopify App API v2024-10 and shopify-app-remix v3.3.2 ## 2024.09.18 - [850](https://github.com/Shopify/shopify-app-template-remix/pull/850) Removed "~" import alias ## 2024.09.17 - [842](https://github.com/Shopify/shopify-app-template-remix/pull/842) Move webhook processing to individual routes ## 2024.08.19 Replaced deprecated `productVariantUpdate` with `productVariantsBulkUpdate` ## v2024.08.06 Allow `SHOP_REDACT` webhook to process without admin context ## v2024.07.16 Started tracking changes and releases using calver ================================================ FILE: Dockerfile ================================================ FROM node:18-alpine RUN apk add --no-cache openssl EXPOSE 3000 WORKDIR /app ENV NODE_ENV=production COPY package.json package-lock.json* ./ RUN npm ci --omit=dev && npm cache clean --force # Remove CLI packages since we don't need them in production by default. # Remove this line if you want to run CLI commands in your container. RUN npm remove @shopify/cli COPY . . RUN npm run build CMD ["npm", "run", "docker-start"] ================================================ FILE: README.md ================================================ # Shopify App Template - Remix > [!NOTE] > **Remix is now React Router.** As of [React Router v7](https://remix.run/blog/merging-remix-and-react-router), Remix and React Router have merged. > > For new projects, use the **[Shopify App Template - React Router](https://github.com/Shopify/shopify-app-template-react-router)** instead. > > To migrate your existing Remix app, follow the **[migration guide](https://github.com/Shopify/shopify-app-template-react-router/wiki/Upgrading-from-Remix)**. This is a template for building a [Shopify app](https://shopify.dev/docs/apps/getting-started) using the [Remix](https://remix.run) framework. Rather than cloning this repo, you can use your preferred package manager and the Shopify CLI with [these steps](https://shopify.dev/docs/apps/getting-started/create). Visit the [`shopify.dev` documentation](https://shopify.dev/docs/api/shopify-app-remix) for more details on the Remix app package. ## Quick start ### Prerequisites Before you begin, you'll need the following: 1. **Node.js**: [Download and install](https://nodejs.org/en/download/) it if you haven't already. 2. **Shopify Partner Account**: [Create an account](https://partners.shopify.com/signup) if you don't have one. 3. **Test Store**: Set up either a [development store](https://help.shopify.com/en/partners/dashboard/development-stores#create-a-development-store) or a [Shopify Plus sandbox store](https://help.shopify.com/en/partners/dashboard/managing-stores/plus-sandbox-store) for testing your app. 4. **Shopify CLI**: [Download and install](https://shopify.dev/docs/apps/tools/cli/getting-started) it if you haven't already. ```shell npm install -g @shopify/cli@latest ``` ### Setup ```shell shopify app init --template=https://github.com/Shopify/shopify-app-template-remix ``` ### Local Development ```shell shopify app dev ``` Local development is powered by [the Shopify CLI](https://shopify.dev/docs/apps/tools/cli). It logs into your partners account, connects to an app, provides environment variables, updates remote config, creates a tunnel and provides commands to generate extensions. ### Authenticating and querying data To authenticate and query data you can use the `shopify` const that is exported from `/app/shopify.server.js`: ```js export async function loader({ request }) { const { admin } = await shopify.authenticate.admin(request); const response = await admin.graphql(` { products(first: 25) { nodes { title description } } }`); const { data: { products: { nodes }, }, } = await response.json(); return nodes; } ``` This template comes preconfigured with examples of: 1. Setting up your Shopify app in [/app/shopify.server.ts](https://github.com/Shopify/shopify-app-template-remix/blob/main/app/shopify.server.ts) 2. Querying data using Graphql. Please see: [/app/routes/app.\_index.tsx](https://github.com/Shopify/shopify-app-template-remix/blob/main/app/routes/app._index.tsx). 3. Responding to webhooks in individual files such as [/app/routes/webhooks.app.uninstalled.tsx](https://github.com/Shopify/shopify-app-template-remix/blob/main/app/routes/webhooks.app.uninstalled.tsx) and [/app/routes/webhooks.app.scopes_update.tsx](https://github.com/Shopify/shopify-app-template-remix/blob/main/app/routes/webhooks.app.scopes_update.tsx) Please read the [documentation for @shopify/shopify-app-remix](https://www.npmjs.com/package/@shopify/shopify-app-remix#authenticating-admin-requests) to understand what other API's are available. ## Deployment ### Application Storage This template uses [Prisma](https://www.prisma.io/) to store session data, by default using an [SQLite](https://www.sqlite.org/index.html) database. The database is defined as a Prisma schema in `prisma/schema.prisma`. This use of SQLite works in production if your app runs as a single instance. The database that works best for you depends on the data your app needs and how it is queried. You can run your database of choice on a server yourself or host it with a SaaS company. Here's a short list of databases providers that provide a free tier to get started: | Database | Type | Hosters | | ---------- | ---------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | MySQL | SQL | [Digital Ocean](https://www.digitalocean.com/products/managed-databases-mysql), [Planet Scale](https://planetscale.com/), [Amazon Aurora](https://aws.amazon.com/rds/aurora/), [Google Cloud SQL](https://cloud.google.com/sql/docs/mysql) | | PostgreSQL | SQL | [Digital Ocean](https://www.digitalocean.com/products/managed-databases-postgresql), [Amazon Aurora](https://aws.amazon.com/rds/aurora/), [Google Cloud SQL](https://cloud.google.com/sql/docs/postgres) | | Redis | Key-value | [Digital Ocean](https://www.digitalocean.com/products/managed-databases-redis), [Amazon MemoryDB](https://aws.amazon.com/memorydb/) | | MongoDB | NoSQL / Document | [Digital Ocean](https://www.digitalocean.com/products/managed-databases-mongodb), [MongoDB Atlas](https://www.mongodb.com/atlas/database) | To use one of these, you can use a different [datasource provider](https://www.prisma.io/docs/reference/api-reference/prisma-schema-reference#datasource) in your `schema.prisma` file, or a different [SessionStorage adapter package](https://github.com/Shopify/shopify-api-js/blob/main/packages/shopify-api/docs/guides/session-storage.md). ### Build Remix handles building the app for you, by running the command below with the package manager of your choice: Using yarn: ```shell yarn build ``` Using npm: ```shell npm run build ``` Using pnpm: ```shell pnpm run build ``` ## Hosting When you're ready to set up your app in production, you can follow [our deployment documentation](https://shopify.dev/docs/apps/deployment/web) to host your app on a cloud provider like [Heroku](https://www.heroku.com/) or [Fly.io](https://fly.io/). When you reach the step for [setting up environment variables](https://shopify.dev/docs/apps/deployment/web#set-env-vars), you also need to set the variable `NODE_ENV=production`. ### Hosting on Vercel Using the Vercel Preset is recommended when hosting your Shopify Remix app on Vercel. You'll also want to ensure imports that would normally come from `@remix-run/node` are imported from `@vercel/remix` instead. Learn more about hosting Remix apps on Vercel [here](https://vercel.com/docs/frameworks/remix). ```diff // vite.config.ts import { vitePlugin as remix } from "@remix-run/dev"; import { defineConfig, type UserConfig } from "vite"; import tsconfigPaths from "vite-tsconfig-paths"; + import { vercelPreset } from '@vercel/remix/vite'; installGlobals(); export default defineConfig({ plugins: [ remix({ ignoredRouteFiles: ["**/.*"], + presets: [vercelPreset()], }), tsconfigPaths(), ], }); ``` ## Troubleshooting ### Database tables don't exist If you get this error: ``` The table `main.Session` does not exist in the current database. ``` You need to create the database for Prisma. Run the `setup` script in `package.json` using your preferred package manager. ### Navigating/redirecting breaks an embedded app Embedded Shopify apps must maintain the user session, which can be tricky inside an iFrame. To avoid issues: 1. Use `Link` from `@remix-run/react` or `@shopify/polaris`. Do not use ``. 2. Use the `redirect` helper returned from `authenticate.admin`. Do not use `redirect` from `@remix-run/node` 3. Use `useSubmit` or `
` from `@remix-run/react`. Do not use a lowercase ``. This only applies if your app is embedded, which it will be by default. ### Non Embedded Shopify apps are best when they are embedded in the Shopify Admin, which is how this template is configured. If you have a reason to not embed your app please make the following changes: 1. Ensure `embedded = false` is set in [shopify.app.toml`](./shopify.app.toml). [Docs here](https://shopify.dev/docs/apps/build/cli-for-apps/app-configuration#global). 2. Pass `isEmbeddedApp: false` to `shopifyApp()` in `./app/shopify.server.js|ts`. 3. Change the `isEmbeddedApp` prop to `isEmbeddedApp={false}` for the `AppProvider` in `/app/routes/app.jsx|tsx`. 4. Remove the `@shopify/app-bridge-react` dependency from [package.json](./package.json) and `vite.config.ts|js`. 5. Remove anything imported from `@shopify/app-bridge-react`. For example: `NavMenu`, `TitleBar` and `useAppBridge`. ### OAuth goes into a loop when I change my app's scopes If you change your app's scopes and authentication goes into a loop and fails with a message from Shopify that it tried too many times, you might have forgotten to update your scopes with Shopify. To do that, you can run the `deploy` CLI command. Using yarn: ```shell yarn deploy ``` Using npm: ```shell npm run deploy ``` Using pnpm: ```shell pnpm run deploy ``` ### My shop-specific webhook subscriptions aren't updated If you are registering webhooks in the `afterAuth` hook, using `shopify.registerWebhooks`, you may find that your subscriptions aren't being updated. Instead of using the `afterAuth` hook, the recommended approach is to declare app-specific webhooks in the `shopify.app.toml` file. This approach is easier since Shopify will automatically update changes to webhook subscriptions every time you run `deploy` (e.g: `npm run deploy`). Please read these guides to understand more: 1. [app-specific vs shop-specific webhooks](https://shopify.dev/docs/apps/build/webhooks/subscribe#app-specific-subscriptions) 2. [Create a subscription tutorial](https://shopify.dev/docs/apps/build/webhooks/subscribe/get-started?framework=remix&deliveryMethod=https) If you do need shop-specific webhooks, please keep in mind that the package calls `afterAuth` in 2 scenarios: - After installing the app - When an access token expires During normal development, the app won't need to re-authenticate most of the time, so shop-specific subscriptions aren't updated. To force your app to update the subscriptions, you can uninstall and reinstall it in your development store. That will force the OAuth process and call the `afterAuth` hook. ### Admin created webhook failing HMAC validation Webhooks subscriptions created in the [Shopify admin](https://help.shopify.com/en/manual/orders/notifications/webhooks) will fail HMAC validation. This is because the webhook payload is not signed with your app's secret key. There are 2 solutions: 1. Use [app-specific webhooks](https://shopify.dev/docs/apps/build/webhooks/subscribe#app-specific-subscriptions) defined in your toml file instead (recommended) 2. Create [webhook subscriptions](https://shopify.dev/docs/api/shopify-app-remix/v1/guide-webhooks) using the `shopifyApp` object. Test your webhooks with the [Shopify CLI](https://shopify.dev/docs/apps/tools/cli/commands#webhook-trigger) or by triggering events manually in the Shopify admin(e.g. Updating the product title to trigger a `PRODUCTS_UPDATE`). ### Incorrect GraphQL Hints By default the [graphql.vscode-graphql](https://marketplace.visualstudio.com/items?itemName=GraphQL.vscode-graphql) extension for VS Code will assume that GraphQL queries or mutations are for the [Shopify Admin API](https://shopify.dev/docs/api/admin). This is a sensible default, but it may not be true if: 1. You use another Shopify API such as the storefront API. 2. You use a third party GraphQL API. in this situation, please update the [.graphqlrc.ts](https://github.com/Shopify/shopify-app-template-remix/blob/main/.graphqlrc.ts) config. ### First parameter has member 'readable' that is not a ReadableStream. See [hosting on Vercel](#hosting-on-vercel). ### Admin object undefined on webhook events triggered by the CLI When you trigger a webhook event using the Shopify CLI, the `admin` object will be `undefined`. This is because the CLI triggers an event with a valid, but non-existent, shop. The `admin` object is only available when the webhook is triggered by a shop that has installed the app. Webhooks triggered by the CLI are intended for initial experimentation testing of your webhook configuration. For more information on how to test your webhooks, see the [Shopify CLI documentation](https://shopify.dev/docs/apps/tools/cli/commands#webhook-trigger). ### Using Defer & await for streaming responses To test [streaming using defer/await](https://remix.run/docs/en/main/guides/streaming) during local development you'll need to use the Shopify CLI slightly differently: 1. First setup ngrok: https://ngrok.com/product/secure-tunnels 2. Create an ngrok tunnel on port 8080: `ngrok http 8080`. 3. Copy the forwarding address. This should be something like: `https://f355-2607-fea8-bb5c-8700-7972-d2b5-3f2b-94ab.ngrok-free.app` 4. In a separate terminal run `yarn shopify app dev --tunnel-url=TUNNEL_URL:8080` replacing `TUNNEL_URL` for the address you copied in step 3. By default the CLI uses a cloudflare tunnel. Unfortunately it cloudflare tunnels wait for the Response stream to finish, then sends one chunk. This will not affect production, since tunnels are only for local development. ### Using MongoDB and Prisma By default this template uses SQLlite as the database. It is recommended to move to a persisted database for production. If you choose to use MongoDB, you will need to make some modifications to the schema and prisma configuration. For more information please see the [Prisma MongoDB documentation](https://www.prisma.io/docs/orm/overview/databases/mongodb). Alternatively you can use a MongDB database directly with the [MongoDB session storage adapter](https://github.com/Shopify/shopify-app-js/tree/main/packages/apps/session-storage/shopify-app-session-storage-mongodb). #### Mapping the id field In MongoDB, an ID must be a single field that defines an @id attribute and a @map("\_id") attribute. The prisma adapter expects the ID field to be the ID of the session, and not the \_id field of the document. To make this work you can add a new field to the schema that maps the \_id field to the id field. For more information see the [Prisma documentation](https://www.prisma.io/docs/orm/prisma-schema/data-model/models#defining-an-id-field) ```prisma model Session { session_id String @id @default(auto()) @map("_id") @db.ObjectId id String @unique ... } ``` #### Error: The "mongodb" provider is not supported with this command MongoDB does not support the [prisma migrate](https://www.prisma.io/docs/orm/prisma-migrate/understanding-prisma-migrate/overview) command. Instead, you can use the [prisma db push](https://www.prisma.io/docs/orm/reference/prisma-cli-reference#db-push) command and update the `shopify.web.toml` file with the following commands. If you are using MongoDB please see the [Prisma documentation](https://www.prisma.io/docs/orm/overview/databases/mongodb) for more information. ```toml [commands] predev = "npx prisma generate && npx prisma db push" dev = "npm exec remix vite:dev" ``` #### Prisma needs to perform transactions, which requires your mongodb server to be run as a replica set See the [Prisma documentation](https://www.prisma.io/docs/getting-started/setup-prisma/start-from-scratch/mongodb/connect-your-database-node-mongodb) for connecting to a MongoDB database. ### I want to use Polaris v13.0.0 or higher Currently, this template is set up to work on node v18.20 or higher. However, `@shopify/polaris` is limited to v12 because v13 can only run on node v20+. You don't have to make any changes to the code in order to be able to upgrade Polaris to v13, but you'll need to do the following: - Upgrade your node version to v20.10 or higher. - Update your `Dockerfile` to pull `FROM node:20-alpine` instead of `node:18-alpine` ### "nbf" claim timestamp check failed This error will occur of the `nbf` claim timestamp check failed. This is because the JWT token is expired. If you are consistently getting this error, it could be that the clock on your machine is not in sync with the server. To fix this ensure you have enabled `Set time and date automatically` in the `Date and Time` settings on your computer. ## Benefits Shopify apps are built on a variety of Shopify tools to create a great merchant experience. The Remix app template comes with the following out-of-the-box functionality: - [OAuth](https://github.com/Shopify/shopify-app-js/tree/main/packages/shopify-app-remix#authenticating-admin-requests): Installing the app and granting permissions - [GraphQL Admin API](https://github.com/Shopify/shopify-app-js/tree/main/packages/shopify-app-remix#using-the-shopify-admin-graphql-api): Querying or mutating Shopify admin data - [Webhooks](https://github.com/Shopify/shopify-app-js/tree/main/packages/shopify-app-remix#authenticating-webhook-requests): Callbacks sent by Shopify when certain events occur - [AppBridge](https://shopify.dev/docs/api/app-bridge): This template uses the next generation of the Shopify App Bridge library which works in unison with previous versions. - [Polaris](https://polaris.shopify.com/): Design system that enables apps to create Shopify-like experiences ## Tech Stack This template uses [Remix](https://remix.run). The following Shopify tools are also included to ease app development: - [Shopify App Remix](https://shopify.dev/docs/api/shopify-app-remix) provides authentication and methods for interacting with Shopify APIs. - [Shopify App Bridge](https://shopify.dev/docs/apps/tools/app-bridge) allows your app to seamlessly integrate your app within Shopify's Admin. - [Polaris React](https://polaris.shopify.com/) is a powerful design system and component library that helps developers build high quality, consistent experiences for Shopify merchants. - [Webhooks](https://github.com/Shopify/shopify-app-js/tree/main/packages/shopify-app-remix#authenticating-webhook-requests): Callbacks sent by Shopify when certain events occur - [Polaris](https://polaris.shopify.com/): Design system that enables apps to create Shopify-like experiences ## Resources - [Remix Docs](https://remix.run/docs/en/v1) - [Shopify App Remix](https://shopify.dev/docs/api/shopify-app-remix) - [Introduction to Shopify apps](https://shopify.dev/docs/apps/getting-started) - [App authentication](https://shopify.dev/docs/apps/auth) - [Shopify CLI](https://shopify.dev/docs/apps/tools/cli) - [App extensions](https://shopify.dev/docs/apps/app-extensions/list) - [Shopify Functions](https://shopify.dev/docs/api/functions) - [Getting started with internationalizing your app](https://shopify.dev/docs/apps/best-practices/internationalization/getting-started) ================================================ FILE: app/db.server.ts ================================================ import { PrismaClient } from "@prisma/client"; declare global { var prismaGlobal: PrismaClient; } if (process.env.NODE_ENV !== "production") { if (!global.prismaGlobal) { global.prismaGlobal = new PrismaClient(); } } const prisma = global.prismaGlobal ?? new PrismaClient(); export default prisma; ================================================ FILE: app/entry.server.tsx ================================================ import { PassThrough } from "stream"; import { renderToPipeableStream } from "react-dom/server"; import { RemixServer } from "@remix-run/react"; import { createReadableStreamFromReadable, type EntryContext, } from "@remix-run/node"; import { isbot } from "isbot"; import { addDocumentResponseHeaders } from "./shopify.server"; export const streamTimeout = 5000; export default async function handleRequest( request: Request, responseStatusCode: number, responseHeaders: Headers, remixContext: EntryContext ) { addDocumentResponseHeaders(request, responseHeaders); const userAgent = request.headers.get("user-agent"); const callbackName = isbot(userAgent ?? '') ? "onAllReady" : "onShellReady"; return new Promise((resolve, reject) => { const { pipe, abort } = renderToPipeableStream( , { [callbackName]: () => { const body = new PassThrough(); const stream = createReadableStreamFromReadable(body); responseHeaders.set("Content-Type", "text/html"); resolve( new Response(stream, { headers: responseHeaders, status: responseStatusCode, }) ); pipe(body); }, onShellError(error) { reject(error); }, onError(error) { responseStatusCode = 500; console.error(error); }, } ); // Automatically timeout the React renderer after 6 seconds, which ensures // React has enough time to flush down the rejected boundary contents setTimeout(abort, streamTimeout + 1000); }); } ================================================ FILE: app/globals.d.ts ================================================ declare module "*.css"; ================================================ FILE: app/root.tsx ================================================ import { Links, Meta, Outlet, Scripts, ScrollRestoration, } from "@remix-run/react"; export default function App() { return ( ); } ================================================ FILE: app/routes/_index/route.tsx ================================================ import type { LoaderFunctionArgs } from "@remix-run/node"; import { redirect } from "@remix-run/node"; import { Form, useLoaderData } from "@remix-run/react"; import { login } from "../../shopify.server"; import styles from "./styles.module.css"; export const loader = async ({ request }: LoaderFunctionArgs) => { const url = new URL(request.url); if (url.searchParams.get("shop")) { throw redirect(`/app?${url.searchParams.toString()}`); } return { showForm: Boolean(login) }; }; export default function App() { const { showForm } = useLoaderData(); return (

A short heading about [your app]

A tagline about [your app] that describes your value proposition.

{showForm && ( )}
  • Product feature. Some detail about your feature and its benefit to your customer.
  • Product feature. Some detail about your feature and its benefit to your customer.
  • Product feature. Some detail about your feature and its benefit to your customer.
); } ================================================ FILE: app/routes/_index/styles.module.css ================================================ .index { align-items: center; display: flex; justify-content: center; height: 100%; width: 100%; text-align: center; padding: 1rem; } .heading, .text { padding: 0; margin: 0; } .text { font-size: 1.2rem; padding-bottom: 2rem; } .content { display: grid; gap: 2rem; } .form { display: flex; align-items: center; justify-content: flex-start; margin: 0 auto; gap: 1rem; } .label { display: grid; gap: 0.2rem; max-width: 20rem; text-align: left; font-size: 1rem; } .input { padding: 0.4rem; } .button { padding: 0.4rem; } .list { list-style: none; padding: 0; padding-top: 3rem; margin: 0; display: flex; gap: 2rem; } .list > li { max-width: 20rem; text-align: left; } @media only screen and (max-width: 50rem) { .list { display: block; } .list > li { padding-bottom: 1rem; } } ================================================ FILE: app/routes/app._index.tsx ================================================ import { useEffect } from "react"; import type { ActionFunctionArgs, LoaderFunctionArgs } from "@remix-run/node"; import { useFetcher } from "@remix-run/react"; import { Page, Layout, Text, Card, Button, BlockStack, Box, List, Link, InlineStack, } from "@shopify/polaris"; import { TitleBar, useAppBridge } from "@shopify/app-bridge-react"; import { authenticate } from "../shopify.server"; export const loader = async ({ request }: LoaderFunctionArgs) => { await authenticate.admin(request); return null; }; export const action = async ({ request }: ActionFunctionArgs) => { const { admin } = await authenticate.admin(request); const color = ["Red", "Orange", "Yellow", "Green"][ Math.floor(Math.random() * 4) ]; const response = await admin.graphql( `#graphql mutation populateProduct($product: ProductCreateInput!) { productCreate(product: $product) { product { id title handle status variants(first: 10) { edges { node { id price barcode createdAt } } } } } }`, { variables: { product: { title: `${color} Snowboard`, }, }, }, ); const responseJson = await response.json(); const product = responseJson.data!.productCreate!.product!; const variantId = product.variants.edges[0]!.node!.id!; const variantResponse = await admin.graphql( `#graphql mutation shopifyRemixTemplateUpdateVariant($productId: ID!, $variants: [ProductVariantsBulkInput!]!) { productVariantsBulkUpdate(productId: $productId, variants: $variants) { productVariants { id price barcode createdAt } } }`, { variables: { productId: product.id, variants: [{ id: variantId, price: "100.00" }], }, }, ); const variantResponseJson = await variantResponse.json(); return { product: responseJson!.data!.productCreate!.product, variant: variantResponseJson!.data!.productVariantsBulkUpdate!.productVariants, }; }; export default function Index() { const fetcher = useFetcher(); const shopify = useAppBridge(); const isLoading = ["loading", "submitting"].includes(fetcher.state) && fetcher.formMethod === "POST"; const productId = fetcher.data?.product?.id.replace( "gid://shopify/Product/", "", ); useEffect(() => { if (productId) { shopify.toast.show("Product created"); } }, [productId, shopify]); const generateProduct = () => fetcher.submit({}, { method: "POST" }); return ( Congrats on creating a new Shopify app 🎉 This embedded app template uses{" "} App Bridge {" "} interface examples like an{" "} additional page in the app nav , as well as an{" "} Admin GraphQL {" "} mutation demo, to provide a starting point for app development. Get started with products Generate a product with GraphQL and get the JSON output for that product. Learn more about the{" "} productCreate {" "} mutation in our API references. {fetcher.data?.product && ( )} {fetcher.data?.product && ( <> {" "} productCreate mutation
                        
                          {JSON.stringify(fetcher.data.product, null, 2)}
                        
                      
{" "} productVariantsBulkUpdate mutation
                        
                          {JSON.stringify(fetcher.data.variant, null, 2)}
                        
                      
)}
App template specs Framework Remix Database Prisma Interface Polaris {", "} App Bridge API GraphQL API Next steps Build an{" "} {" "} example app {" "} to get started Explore Shopify’s API with{" "} GraphiQL
); } ================================================ FILE: app/routes/app.additional.tsx ================================================ import { Box, Card, Layout, Link, List, Page, Text, BlockStack, } from "@shopify/polaris"; import { TitleBar } from "@shopify/app-bridge-react"; export default function AdditionalPage() { return ( The app template comes with an additional page which demonstrates how to create multiple pages within app navigation using{" "} App Bridge . To create your own page and have it show up in the app navigation, add a page inside app/routes, and a link to it in the <NavMenu> component found in app/routes/app.jsx. Resources App nav best practices ); } function Code({ children }: { children: React.ReactNode }) { return ( {children} ); } ================================================ FILE: app/routes/app.tsx ================================================ import type { HeadersFunction, LoaderFunctionArgs } from "@remix-run/node"; import { Link, Outlet, useLoaderData, useRouteError } from "@remix-run/react"; import { boundary } from "@shopify/shopify-app-remix/server"; import { AppProvider } from "@shopify/shopify-app-remix/react"; import { NavMenu } from "@shopify/app-bridge-react"; import polarisStyles from "@shopify/polaris/build/esm/styles.css?url"; import { authenticate } from "../shopify.server"; export const links = () => [{ rel: "stylesheet", href: polarisStyles }]; export const loader = async ({ request }: LoaderFunctionArgs) => { await authenticate.admin(request); return { apiKey: process.env.SHOPIFY_API_KEY || "" }; }; export default function App() { const { apiKey } = useLoaderData(); return ( Home Additional page ); } // Shopify needs Remix to catch some thrown responses, so that their headers are included in the response. export function ErrorBoundary() { return boundary.error(useRouteError()); } export const headers: HeadersFunction = (headersArgs) => { return boundary.headers(headersArgs); }; ================================================ FILE: app/routes/auth.$.tsx ================================================ import type { LoaderFunctionArgs } from "@remix-run/node"; import { authenticate } from "../shopify.server"; export const loader = async ({ request }: LoaderFunctionArgs) => { await authenticate.admin(request); return null; }; ================================================ FILE: app/routes/auth.login/error.server.tsx ================================================ import type { LoginError } from "@shopify/shopify-app-remix/server"; import { LoginErrorType } from "@shopify/shopify-app-remix/server"; interface LoginErrorMessage { shop?: string; } export function loginErrorMessage(loginErrors: LoginError): LoginErrorMessage { if (loginErrors?.shop === LoginErrorType.MissingShop) { return { shop: "Please enter your shop domain to log in" }; } else if (loginErrors?.shop === LoginErrorType.InvalidShop) { return { shop: "Please enter a valid shop domain to log in" }; } return {}; } ================================================ FILE: app/routes/auth.login/route.tsx ================================================ import { useState } from "react"; import type { ActionFunctionArgs, LoaderFunctionArgs } from "@remix-run/node"; import { Form, useActionData, useLoaderData } from "@remix-run/react"; import { AppProvider as PolarisAppProvider, Button, Card, FormLayout, Page, Text, TextField, } from "@shopify/polaris"; import polarisTranslations from "@shopify/polaris/locales/en.json"; import polarisStyles from "@shopify/polaris/build/esm/styles.css?url"; import { login } from "../../shopify.server"; import { loginErrorMessage } from "./error.server"; export const links = () => [{ rel: "stylesheet", href: polarisStyles }]; export const loader = async ({ request }: LoaderFunctionArgs) => { const errors = loginErrorMessage(await login(request)); return { errors, polarisTranslations }; }; export const action = async ({ request }: ActionFunctionArgs) => { const errors = loginErrorMessage(await login(request)); return { errors, }; }; export default function Auth() { const loaderData = useLoaderData(); const actionData = useActionData(); const [shop, setShop] = useState(""); const { errors } = actionData || loaderData; return (
Log in
); } ================================================ FILE: app/routes/webhooks.app.scopes_update.tsx ================================================ import type { ActionFunctionArgs } from "@remix-run/node"; import { authenticate } from "../shopify.server"; import db from "../db.server"; export const action = async ({ request }: ActionFunctionArgs) => { const { payload, session, topic, shop } = await authenticate.webhook(request); console.log(`Received ${topic} webhook for ${shop}`); const current = payload.current as string[]; if (session) { await db.session.update({ where: { id: session.id }, data: { scope: current.toString(), }, }); } return new Response(); }; ================================================ FILE: app/routes/webhooks.app.uninstalled.tsx ================================================ import type { ActionFunctionArgs } from "@remix-run/node"; import { authenticate } from "../shopify.server"; import db from "../db.server"; export const action = async ({ request }: ActionFunctionArgs) => { const { shop, session, topic } = await authenticate.webhook(request); console.log(`Received ${topic} webhook for ${shop}`); // Webhook requests can trigger multiple times and after an app has already been uninstalled. // If this webhook already ran, the session may have been deleted previously. if (session) { await db.session.deleteMany({ where: { shop } }); } return new Response(); }; ================================================ FILE: app/routes.ts ================================================ import { flatRoutes } from "@remix-run/fs-routes"; export default flatRoutes(); ================================================ FILE: app/shopify.server.ts ================================================ import "@shopify/shopify-app-remix/adapters/node"; import { ApiVersion, AppDistribution, shopifyApp, } from "@shopify/shopify-app-remix/server"; import { PrismaSessionStorage } from "@shopify/shopify-app-session-storage-prisma"; import prisma from "./db.server"; const shopify = shopifyApp({ apiKey: process.env.SHOPIFY_API_KEY, apiSecretKey: process.env.SHOPIFY_API_SECRET || "", apiVersion: ApiVersion.January25, scopes: process.env.SCOPES?.split(","), appUrl: process.env.SHOPIFY_APP_URL || "", authPathPrefix: "/auth", sessionStorage: new PrismaSessionStorage(prisma), distribution: AppDistribution.AppStore, future: { unstable_newEmbeddedAuthStrategy: true, expiringOfflineAccessTokens: true, }, ...(process.env.SHOP_CUSTOM_DOMAIN ? { customShopDomains: [process.env.SHOP_CUSTOM_DOMAIN] } : {}), }); export default shopify; export const apiVersion = ApiVersion.January25; export const addDocumentResponseHeaders = shopify.addDocumentResponseHeaders; export const authenticate = shopify.authenticate; export const unauthenticated = shopify.unauthenticated; export const login = shopify.login; export const registerWebhooks = shopify.registerWebhooks; export const sessionStorage = shopify.sessionStorage; ================================================ FILE: env.d.ts ================================================ /// /// ================================================ FILE: extensions/.gitkeep ================================================ ================================================ FILE: package.json ================================================ { "name": "app", "private": true, "scripts": { "build": "remix vite:build", "dev": "shopify app dev", "config:link": "shopify app config link", "generate": "shopify app generate", "deploy": "shopify app deploy", "config:use": "shopify app config use", "env": "shopify app env", "start": "remix-serve ./build/server/index.js", "docker-start": "npm run setup && npm run start", "setup": "prisma generate && prisma migrate deploy", "lint": "eslint --cache --cache-location ./node_modules/.cache/eslint .", "shopify": "shopify", "prisma": "prisma", "graphql-codegen": "graphql-codegen", "vite": "vite" }, "type": "module", "engines": { "node": ">=20.19 <22 || >=22.12" }, "dependencies": { "@prisma/client": "^6.2.1", "@remix-run/dev": "^2.16.1", "@remix-run/fs-routes": "^2.16.1", "@remix-run/node": "^2.16.1", "@remix-run/react": "^2.16.1", "@remix-run/serve": "^2.16.1", "@shopify/app-bridge-react": "^4.1.6", "@shopify/polaris": "^12.0.0", "@shopify/shopify-app-remix": "^4.1.0", "@shopify/shopify-app-session-storage-prisma": "^8.0.0", "isbot": "^5.1.0", "prisma": "^6.2.1", "react": "^18.2.0", "react-dom": "^18.2.0", "vite-tsconfig-paths": "^5.0.1" }, "devDependencies": { "@remix-run/eslint-config": "^2.16.1", "@remix-run/route-config": "^2.16.1", "@shopify/api-codegen-preset": "^1.1.1", "@types/eslint": "^9.6.1", "@types/node": "^22.2.0", "@types/react": "^18.2.31", "@types/react-dom": "^18.2.14", "eslint": "^8.42.0", "eslint-config-prettier": "^10.0.1", "prettier": "^3.2.4", "typescript": "^5.2.2", "vite": "^6.2.2" }, "workspaces": { "packages": [ "extensions/*" ] }, "trustedDependencies": [ "@shopify/plugin-cloudflare" ], "resolutions": { "@graphql-tools/url-loader": "8.0.16", "@graphql-codegen/client-preset": "4.7.0", "@graphql-codegen/typescript-operations": "4.5.0", "minimatch": "9.0.5", "vite": "^6.2.2" }, "overrides": { "@graphql-tools/url-loader": "8.0.16", "@graphql-codegen/client-preset": "4.7.0", "@graphql-codegen/typescript-operations": "4.5.0", "minimatch": "9.0.5", "vite": "^6.2.2" } } ================================================ FILE: prisma/migrations/20240530213853_create_session_table/migration.sql ================================================ -- CreateTable CREATE TABLE "Session" ( "id" TEXT NOT NULL PRIMARY KEY, "shop" TEXT NOT NULL, "state" TEXT NOT NULL, "isOnline" BOOLEAN NOT NULL DEFAULT false, "scope" TEXT, "expires" DATETIME, "accessToken" TEXT NOT NULL, "userId" BIGINT, "firstName" TEXT, "lastName" TEXT, "email" TEXT, "accountOwner" BOOLEAN NOT NULL DEFAULT false, "locale" TEXT, "collaborator" BOOLEAN DEFAULT false, "emailVerified" BOOLEAN DEFAULT false, "refreshToken" TEXT, "refreshTokenExpires" DATETIME ); ================================================ FILE: prisma/schema.prisma ================================================ // This is your Prisma schema file, // learn more about it in the docs: https://pris.ly/d/prisma-schema generator client { provider = "prisma-client-js" } // Note that some adapters may set a maximum length for the String type by default, please ensure your strings are long // enough when changing adapters. // See https://www.prisma.io/docs/orm/reference/prisma-schema-reference#string for more information datasource db { provider = "sqlite" url = "file:dev.sqlite" } model Session { id String @id shop String state String isOnline Boolean @default(false) scope String? expires DateTime? accessToken String userId BigInt? firstName String? lastName String? email String? accountOwner Boolean @default(false) locale String? collaborator Boolean? @default(false) emailVerified Boolean? @default(false) refreshToken String? refreshTokenExpires DateTime? } ================================================ FILE: shopify.app.toml ================================================ # This file stores configurations for your Shopify app. client_id = "" [access_scopes] # Learn more at https://shopify.dev/docs/apps/tools/cli/configuration#access_scopes scopes = "write_products" [webhooks] api_version = "2024-10" # Handled by: /app/routes/webhooks.app.uninstalled.tsx [[webhooks.subscriptions]] uri = "/webhooks/app/uninstalled" topics = ["app/uninstalled"] # Handled by: /app/routes/webhooks.app.scopes_update.tsx [[webhooks.subscriptions]] topics = [ "app/scopes_update" ] uri = "/webhooks/app/scopes_update" # Webhooks can have filters # Only receive webhooks for product updates with a product price >= 10.00 # See: https://shopify.dev/docs/apps/build/webhooks/customize/filters # [[webhooks.subscriptions]] # topics = ["products/update"] # uri = "/webhooks/products/update" # filter = "variants.price:>=10.00" # Mandatory compliance topic for public apps only # See: https://shopify.dev/docs/apps/build/privacy-law-compliance # [[webhooks.subscriptions]] # uri = "/webhooks/customers/data_request" # compliance_topics = ["customers/data_request"] # [[webhooks.subscriptions]] # uri = "/webhooks/customers/redact" # compliance_topics = ["customers/redact"] # [[webhooks.subscriptions]] # uri = "/webhooks/shop/redact" # compliance_topics = ["shop/redact"] ================================================ FILE: shopify.web.toml.liquid ================================================ name = "remix" roles = ["frontend", "backend"] webhooks_path = "/webhooks/app/uninstalled" {%- assign exec = dependency_manager | append: ' exec' -%} {%- if dependency_manager == 'yarn' -%} {%- assign exec = 'yarn' -%} {%- endif %} [commands] predev = "{{ exec }} prisma generate" dev = "{{ exec }} prisma migrate deploy && {{ exec }} remix vite:dev" ================================================ FILE: tsconfig.json ================================================ { "include": ["env.d.ts", "**/*.ts", "**/*.tsx"], "compilerOptions": { "lib": ["DOM", "DOM.Iterable", "ES2022"], "strict": true, "skipLibCheck": true, "isolatedModules": true, "allowSyntheticDefaultImports": true, "removeComments": false, "forceConsistentCasingInFileNames": true, "noEmit": true, "allowJs": true, "resolveJsonModule": true, "jsx": "react-jsx", "module": "ESNext", "moduleResolution": "Bundler", "target": "ES2022", "baseUrl": ".", "types": ["node"] } } ================================================ FILE: vite.config.ts ================================================ import { vitePlugin as remix } from "@remix-run/dev"; import { installGlobals } from "@remix-run/node"; import { defineConfig, type UserConfig } from "vite"; import tsconfigPaths from "vite-tsconfig-paths"; installGlobals({ nativeFetch: true }); // Related: https://github.com/remix-run/remix/issues/2835#issuecomment-1144102176 // Replace the HOST env var with SHOPIFY_APP_URL so that it doesn't break the remix server. The CLI will eventually // stop passing in HOST, so we can remove this workaround after the next major release. if ( process.env.HOST && (!process.env.SHOPIFY_APP_URL || process.env.SHOPIFY_APP_URL === process.env.HOST) ) { process.env.SHOPIFY_APP_URL = process.env.HOST; delete process.env.HOST; } const host = new URL(process.env.SHOPIFY_APP_URL || "http://localhost") .hostname; let hmrConfig; if (host === "localhost") { hmrConfig = { protocol: "ws", host: "localhost", port: 64999, clientPort: 64999, }; } else { hmrConfig = { protocol: "wss", host: host, port: parseInt(process.env.FRONTEND_PORT!) || 8002, clientPort: 443, }; } export default defineConfig({ server: { allowedHosts: [host], cors: { preflightContinue: true, }, port: Number(process.env.PORT || 3000), hmr: hmrConfig, fs: { // See https://vitejs.dev/config/server-options.html#server-fs-allow for more information allow: ["app", "node_modules"], }, }, plugins: [ remix({ ignoredRouteFiles: ["**/.*"], future: { v3_fetcherPersist: true, v3_relativeSplatPath: true, v3_throwAbortReason: true, v3_lazyRouteDiscovery: true, v3_singleFetch: false, v3_routeConfig: true, }, }), tsconfigPaths(), ], build: { assetsInlineLimit: 0, }, optimizeDeps: { include: ["@shopify/app-bridge-react", "@shopify/polaris"], }, }) satisfies UserConfig;