Shopify Remix is an application that is used by Shopify to build custom storefront experiences for developers to meet their needs. A typical feature that can be found in many Shopify apps is the need to show data from an external MySQL database.
In this tutorial, we will explain how to easily connect your Shopify Remix application to a MySQL database and fetch and render data effectively using GraphQL, Shopify’s API. The example model used in this tutorial is a ‘User’ table, but these concepts can be applied to any data structure.
Steps to Display MySQL Database Data into your Shopify Remix App:
Step 1: Setting up your Data Model
The first step is to define your data model. For our example, we’ll use a ‘User’ table with columns ‘id’ and ‘name’. Ensure your MySQL database is set up and contains the necessary data. Here’s an example model definition:
For example you have User table :
model User { id Int @id @default(autoincrement()) name String }
This model defines a ‘User’ table with columns for ‘id’ and ‘name’. The @id and @default(autoincrement()) annotations signify that ‘id’ is the primary key and automatically increments with each new entry.
Step 2: Fetching Data From Database
To retrieve data from our MySQL database, we will use the loader function in the route file. This function uses a library such as Prisma to search the database and retrieve the user data. This data is then made available in the component through UseLoaderData. Here’s an example of the loader function:
// Example loader function in route file
import { useLoaderData } from "@remix-run/react"; import { json } from "@remix-run/node"; import db from "../db.server"; export async function loader() { const users = await db.user.findMany(); return json({ users }); }
Step 3: Displaying Data in your Remix App
Now that you have the data, it’s time to display it in your Shopify Remix app. The index component showcases how to use the fetched user data within a Polaris Card and List.
// Example index component in route file
import { useLoaderData } from "@remix-run/react"; import { Card, Page, List } from "@shopify/polaris"; export default function index() { const { users } = useLoaderData(); return ( <Page> <Card> {users.map((user) => ( <List type="bullet" key={user.id}> <List.Item>{user.name}</List.Item> </List> ))} </Card> </Page> ); }
Conclusion:
Following this tutorial, you will be able to fetch MySQL database data into your Shopify Remix app via GraphQL. This process can be applied to any data structure and forms a strong base for developing dynamic and data intensive web applications. Expand this knowledge to other areas of Shopify development and discover further opportunities to improve your app.
Also learn, How to Integrate MySQL Database to a Shopify Remix App.
Happy Coding!