Next.jsを使ったE-commerceプロジェクトの構築

この記事では、Next.jsを使用してE-commerceプロジェクトを構築する方法について説明します。

目次

  1. プロジェクトの準備
  2. ページコンポーネントの作成
  3. 商品データの取得と表示
  4. ショッピングカートの実装
  5. 決済機能の統合
  6. デプロイ

1. プロジェクトの準備

まず、プロジェクトの準備として、create-next-appを使用して、Next.jsのアプリケーションを作成します。

npx create-next-app e-commerce-project
cd e-commerce-project

次に、必要なパッケージをインストールします。

npm install @material-ui/core commerce.js

これでプロジェクトのセットアップが完了しました。

2. ページコンポーネントの作成

プロジェクトのメインページとなるindex.jsファイルをpagesディレクトリに作成します。

import Head from 'next/head'
import { Container, Grid } from '@material-ui/core'
import Product from '../components/Product'

export default function Home({ products }) {
  return (
    <>
      <Head>
        <title>E-commerce Project</title>
      </Head>
      
      <Container>
        <Grid container spacing={3}>
          {products.map(product => (
            <Grid item key={product.id} xs={12} sm={6} md={4}>
              <Product product={product} />
            </Grid>
          ))}
        </Grid>
      </Container>
    </>
  )
}

3. 商品データの取得と表示

Commerce.js APIから商品データを取得し、それをProductコンポーネントで表示します。

// pages/api/products.js

import Commerce from '@chec/commerce.js'

export default async function products(req, res) {
  const commerce = new Commerce(process.env.COMMERCE_JS_PUBLIC_KEY)
  const { data } = await commerce.products.list()
  
  res.status(200).json(data)
}
// components/Product.js

import { Card, CardActionArea, CardContent, CardMedia, Typography } from '@material-ui/core'

export default function Product({ product }) {
  return (
    <Card>
      <CardActionArea>
        <CardMedia
          component="img"
          alt={product.name}
          height="140"
          image={product.media.source}
          title={product.name}
        />
        <CardContent>
          <Typography gutterBottom variant="h5" component="h2">
            {product.name}
          </Typography>
          <Typography variant="body2" color="textSecondary" component="p">
            {product.description}
          </Typography>
        </CardContent>
      </CardActionArea>
    </Card>
  )
}

4. ショッピングカートの実装

Next, implement the shopping cart by creating a Cart component and linking it to the Product component.

// components/Cart.js

import { useState, useEffect } from 'react'
import { Container, Button, Grid, Typography } from '@material-ui/core'
import Product from './Product'

export default function Cart({ cart }) {
  return (
    <Container>
      <Grid container spacing={3}>
        {cart.line_items.map(item => (
          <Grid item key={item.id} xs={12} sm={6} md={4}>
            <Product product={item} />
          </Grid>
        ))}
      </Grid>
    </Container>
  )
}

5. 決済機能の統合

この章では、Stripe を使用して決済機能を追加します。まず、Stripeのパッケージをインストールします。

npm install @stripe/stripe-js @stripe/react-stripe-js

次に、決済ページを作成し、pages/checkout.jsに配置します。

import { Elements } from '@stripe/react-stripe-js'
import { loadStripe } from '@stripe/stripe-js'

import CheckoutForm from '../components/CheckoutForm'

const stripePromise = loadStripe(process.env.STRIPE_PUBLISHABLE_KEY)

function Checkout() {
  return (
    <Elements stripe={stripePromise}>
      <CheckoutForm />
    </Elements>
  )
}

export default Checkout

最後に、チェックアウトフォームを作成し、決済情報をStripeに送信します。

// components/CheckoutForm.js

import { useState } from 'react'
import { CardElement, useElements, useStripe } from '@stripe/react-stripe-js'
import { Button, Typography } from '@material-ui/core'

export default function CheckoutForm() {
  const [error, setError] = useState(null)
  const [processing, setProcessing] = useState(false)
  const stripe = useStripe()
  const elements = useElements()

  const handleSubmit = async (event) => {
    event.preventDefault()

    setProcessing(true)

    const payload = await stripe.createToken(elements.getElement(CardElement))

    if (payload.error) {
      setError(payload.error.message)
      setProcessing(false)
    } else {
      // Process payment (success)
    }
  }

  return (
    <form onSubmit={handleSubmit}>
      <CardElement />
      <Button type="submit" disabled={!stripe || processing}>
        Pay Now
      </Button>
      
      {error && (
        <Typography color="error">
          {error}
        </Typography>
      )}
    </form>
  )
}

6. デプロイ

すべての機能が実装されたら、Vercel などのプラットフォームを使用してプロジェクトをデプロイできます。

プロジェクトルートに.env.localファイルを作成し、環境変数を設定します。

NEXT_PUBLIC_COMMERCE_JS_PUBLIC_KEY=your_commerce_js_public_key
STRIPE_PUBLISHABLE_KEY=your_stripe_publishable_key

そして、デプロイコマンドを実行します。

vercel

これで、E-commerceプロジェクトが完全に完成しました。Next.js, Commerce.js, およびStripeを組み合わせて、ショッピングカートと決済機能を備えたE-commerceウェブサイトを構築する方法を学びました。今後のプロジェクトでこのスキルが役立つことを願っています。