Skip to content

Building a Shopping Cart with Redwood

Having a shopping cart before you check out is something that good online stores have. It shows all of the items you want to be shipped to you and then you get to check out. It’s important to have this functionality implemented securely so that you aren’t putting users’ information at risk

We’re going to build a quick shopping cart with checkout abilities in Redwood, using Stripe to handle all of the checkout functionality.

There are a couple of things you’ll want to do before we start writing code. First, create a Stripe account if you don’t already have one. Create a Cloudinary account as well because this is where we’ll pull the media for the items from. So go ahead and upload the images or videos you want to use for your items. We’ll be using these two services throughout the app. The last thing you’ll need is a local instance of Postgres. You can find the free install here.

Now we can go ahead and bootstrap the Redwood app by running the following line in a terminal. This will generate a TypeScript project for us.

yarn create redwood-app --typescript shop-checkout

You’ll notice a lot of new files and directories in the shop-checkout folder. The main folders we’ll be working with are api, which holds the back-end code, and web, which holds the front-end code.

Since it’s usually a good practice to start building the business logic first, let’s start writing code for the back-end.

Inside api > db, you’ll find a schema.prisma file. This is where all of your database changes happen. Whenever you make a change to a model in this file, you’ll need to run a migration for that change to be reflected in your database.

The first thing we need to do is set up the connection to the database. Update the provider value from sqlite to postgresql. That tells Prisma that we’re working with a Postgres database so it knows what to expect. Then we need to set the right value for DATABASE_URL.

To do this, look for the .env file in the root of the project. You’ll see a line that’s commented out with a DATABASE_URL value. Uncomment that line and update it to match your local connection string. That might look something like this where shop is the name we’re giving the database.

DATABASE_URL=postgres://admin:postgres@localhost:5432/shop
Code language: JavaScript (javascript)

That’s all we need to connect our back-end to the database. Now we need to define some models for the tables and rows we need data for.

You can delete the UserExample model and add the following models.

model Item {
  id      String  @id @default(uuid())
  name    String
  price   Float
  url     String
  Order   Order?  @relation(fields: [orderId], references: [id])
  orderId String?
}

model Order {
  id         String   @id @default(cuid())
  created_at DateTime
  items      Item[]
  total      Float
}
Code language: JavaScript (javascript)

We’ve created the models for the Item selections customers make in an Order. The main thing to note in these models is the relation between the two of these models. The orderId acts as a foreign key into the Order table. So there can be multiple items associated with one order.

Since we have the models, we can go ahead and run a migration with this command.

yarn rw prisma migrate dev

You’ll be prompted to name this migration after the connection has been established and you can call it anything you want.

To keep the scope of this tutorial in focus, we’re not going to build out the system for users to select items. Instead, we’re going to seed the database with some items and orders to simulate having an order ready for check out.

In api > db, open the seed.js file. This is where we’re going to write our seed data. You can delete all of the commented out code in the main function and add the code for our models.

const ordersData = [
    { createdAt: new Date('09/21/2021'), total: 123.34 },
    { createdAt: new Date('04/21/2021'), total: 424.13 },
  ]
  const itemsData = [
    { name: 'Spoon', price: 34.99, url: 'https://res.cloudinary.com/milecia/image/upload/v1606580786/samples/landscapes/landscape-panorama.jpg' },
    { name: 'Blow Dryer', price: 89.99, url: 'https://res.cloudinary.com/milecia/image/upload/v1606580785/samples/landscapes/nature-mountains.jpg' },
    { name: 'Pet Bed', price: 57.99, url: 'https://res.cloudinary.com/milecia/image/upload/v1606580779/samples/landscapes/architecture-signs.jpg' },
    { name: 'Wicker Chair', price: 124.99, url: 'https://res.cloudinary.com/milecia/image/upload/v1606580776/samples/landscapes/girl-urban-view.jpg' },
    { name: 'Paint', price: 42.99, url: 'https://res.cloudinary.com/milecia/video/upload/v1606580790/elephant_herd.mp4' },
    { name: 'Flooring', price: 15.99, url: 'https://res.cloudinary.com/milecia/video/upload/v1606580788/sea-turtle.mp4' },
  ]

  return Promise.all(
    ordersData.map(async (order) => {
      const record = await db.order.create({
        data: { createdAt: order.createdAt, total: order.total },
      })
      console.log(record)
    }),
    itemsData.map(async (item) => {
      const record = await db.item.create({
        data: {name: item.name, price: item.price, url: item.url, orderId: 'cktm7yt8l00001jxh5f26yg2z'},
      })

      console.log(record)
    })
  )
Code language: JavaScript (javascript)

With this seed data in place, we can go ahead and seed the database with this command.

yarn rw prisma db seed

This will add all of your data to the database, so when we get ready to load the shopping cart view there’s data available for us.

The last thing we need to do on the back-end is add the methods we need to call the data on the front-end. We’ll wrap this up pretty quick with a couple of Redwood commands to generate the GraphQL types and resolvers we need.

yarn rw g sdl item
yarn rw g sdl order

If you take a look in api > src > graphql, you’ll see two new files. Take a look at the items.sdl.ts file and you’ll see all fo the types you need to make your GraphQL queries and mutations.

Now take a look in api > src > services. There are two new folders here that hold a few different files. There are a couple of test files and the main file that holds the resolvers. Open either the items.ts file or the orders.ts file. You’ll see the resolver to get all of the items or orders.

With that, we’ve finished the back-end! Now we can switch our attention to the front-end, where we’ll build a quick shopping cart and check out page.

Before we start working on components, there is a package we’ll need to add in order to work with Stripe. In a terminal, go to the web directory and run this command.

yarn add react-stripe-checkout

This is the only package we needed to install, so we can get started on the shopping cart page.

We’ll use another Redwood command to generate the files we need for the shopping cart. In the terminal, go back to the root of the directory and run this command.

yarn rw g page ShoppingCart /cart

This generates a page component that displays at the /cart route. If you take a look in web > src > page, you’ll see a new folder named ShoppingCartPage. In this folder, there are couple of files related to tests and the main ShoppingCartPage.tsx file. Open this up and delete everything inside of the return statement of the component.

You can keep the <MetaTags> component if you like. I’m just deleting everything to keep things simple.

First, we’ll add a GraphQL query to get the items. You can look up one of the order ids from the seeded data in your Postgres instance.

Remember, this is supposed to be about the shopping cart and checkout experience so we’ll hard-code an order id. In a fully connected app, the order id would probably come from some parameter being passed from another component.

So let’s add that GraphQL query above the ShoppingCartPage component.

export const QUERY = gql`
query Items {
  items {
    name
    price
    url
    orderId
  }
}
`
Code language: JavaScript (javascript)

This will let us get all of the items we have seeded. Next, we need to execute this query so we have the data available and we’re able to filter by order id. At the top of the file, add this import statement.

import { useQuery } from '@redwoodjs/web'
Code language: JavaScript (javascript)

Inside the ShoppingCartPage component, add this code at the top.

const { data, loading } = useQuery(QUERY)

if (loading) {
  return <div>Loading...</div>
}

const orderItems = data.items.filter(item => item.orderId === 'cktm7yt8l00001jxh5f26yg2z')
Code language: JavaScript (javascript)

This will fetch the items from the database and also return a loading state. When the data is loading, we need to handle that condition in the app so it doesn’t crash. That’s why we have that early return statement if the data is still loading.

Once it finishes loading, then we create a new variable to hold all of the items in the order. Now we need to display the info for each item. We’ll add the following return statement to our component.

return (
  <div style={{
    display: 'flex',
    flexDirection: 'row',
    flexWrap: 'wrap'
  }}>
    {orderItems.map(item => {
      return (
        <div style={{
          border: '1px solid',
          margin: '0 12px 24px',
          padding: '24px',
          height: '500px',
          width: '20%'
        }}>
          {item.url.includes('mp4') ?
            <video controls src={item.url} height={200} style={{ maxWidth: '100%' }}></video> :
            <img src={item.url} height={200} style={{ maxWidth: '100%' }} />
          }
          <h2>{item.name}</h2>
          <h3>{item.price}</h3>
        </div>
      )
    })
    }
  </div>
)
Code language: JavaScript (javascript)

We have a couple of styled <div> elements to make the shopping cart look decent. For each of the items in the order, we check if its media is an image or a video and then we create a card to show the media, the name, and the price.

If you start your app with yarn rw dev in a terminal in the root directory and go the ‘cart’ route, you’ll see something similar to this.

picture of the cart with our items in it

Now we need to add the Stripe elements to handle the check out after we click the button we’re about to create.

Let’s start by importing that Stripe package. This is a good place to go grab the ‘Publishable key’ from your Stripe account because you’ll need it for the component we’re about to work with.

import StripeCheckout from 'react-stripe-checkout';
Code language: JavaScript (javascript)

This adds a simple checkout modal on the page when the customer is ready to check out. All of the checkout and payment functionality is bundled into this one component. We’ll add the component above our list of items.

<StripeCheckout
  amount={36694}
  billingAddress
  description={`The ${orderItems.length} items you selected are here`}
 image="https://res.cloudinary.com/milecia/image/upload/v1606580786/samples/landscapes/landscape-panorama.jpg"
  locale="auto"
  name="Your Cart"
  stripeKey={process.env.STRIPE_ID}
  token={processToken}
  zipCode
/>
Code language: HTML, XML (xml)

This component has a ton of props and it would be worthwhile to check out the docs on them. We have the amount which could be calculated dynamically, but you’ll have to watch out for the format expected by the component. Then we include the billingAddress to show this part of the process.

The main two props to note are the stripeKey and the token. The stripeKey is that publishable key you grabbed from your account earlier. You’ll notice that token is a callback that will have the token from the successful Stripe transaction.

We’ll define the method for processToken right above the return statement in our component.

const processToken = (token) => {
  console.log('This is where some back-end things would happen after a successful transaction.')
}
Code language: JavaScript (javascript)

Usually you’ll pass that token to the back-end and do some processing before saving a record to your database. This is out of scope for this particular tutorial, but if you want to learn more about that back-end implementation, check out Stripe’s docs on it.

Everything’s in place and ready to go! If you take a look in your browser, you’ll see a new button in the top left of the page.

checkout button

Go ahead and click the button to see the checkout flow in action.

customer address information

Since we’re using a test account, you’ll see a yellow indicator in the upper right corner of your page that says you’re in test mode. Now if you continue, this will take you to where a customer can input their card info.

customer card information

When you submit, you’ll see a loading icon in the pay button and then a green checkmark confirming the transaction.

order confirmation

With a successful transaction, the token gets passed to the processToken function we made so you’ll see our message in the console.

Now you have a shopping cart with Stripe checkout functionality!

You can see the full code in the shop-checkout folder in this repo and you can see some of this in action in this Code Sandbox.

Knowing how to handle payments is a valuable developer skill because there are so many platforms and applications that rely on payment systems being implemented correctly and securely. It gives you the flexibility to make a site that does everything a customer needs.

Back to top

Featured Post