DEV Community

Cover image for How to set up Stripe with Nextjs
Anjan Shomodder
Anjan Shomodder

Posted on

How to set up Stripe with Nextjs

Create Nextjs project

npx create-next-app <app-name>
Enter fullscreen mode Exit fullscreen mode

Stripe Sandbox

  • Create a Stripe sandbox from the Stripe dashboard
  • Copy the Stripe publishable key and secret key
  • Add the keys to the .env.local file in the project.
NEXT_PUBLIC_STRIPE_PUBLISHABLE_KEY=pk_test_51Ra9j34F0AnCZjIgVY1KAjeZeDwATbLElhomZ4T2kRKaRNtbuQv766PP9HswNnrKpBqEwvJgcBzEJXveEO6COFLR00P76vyj8r
STRIPE_SECRET_KEY=sk_test_51Ra9j34F0AnCZjIgaNUVIzfYaFxTx3eXcSgHwgIdTJrpBKpWnQPlEVPylQLW1Cu8bGJdNQOVyiDnEssjbcVzGXtW005x2fgsEP
Enter fullscreen mode Exit fullscreen mode

You can also check the video tutorial on youtube.

Install Stripe Packages

npm i stripe @stripe/react-stripe-js @stripe/stripe-js
Enter fullscreen mode Exit fullscreen mode
  • stripe: Core packages
  • @stripe/react-stripe-js: React components for Stripe web elements
  • @stripe/stripe-js: Stripe.js library for client-side operations

Create Stripe instances

You need Stripe instances on both the client and server sides.

  • Create a file lib/stripe.js in the root directory
import 'server-only'

import Stripe from 'stripe'

export const stripe = new Stripe(process.env.STRIPE_SECRET_KEY || '')
Enter fullscreen mode Exit fullscreen mode

Explanation:

  • import 'server-only': Ensures this file is only used on the server side. Optional but recommended to prevent accidental client-side usage.
  • new Stripe(...): Initializes the Stripe instance with your secret key from environment variables.

  • Create a file lib/stripeClient.js in the root directory

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

export const stripePromise = loadStripe(
  process.env.NEXT_PUBLIC_STRIPE_PUBLISHABLE_KEY || '',
)
Enter fullscreen mode Exit fullscreen mode

Explanation:

  • loadStripe(...): Loads the Stripe.js library with your publishable key, which is used on the client side.
  • loadStripe returns a promise that resolves to a Stripe object, which will be used on the client side.

That's it! You now have the setup for integrating Stripe with your Next.js application.

If this video helped you, please subscribe to my YouTube channel for more content like this. If you have any questions or suggestions, feel free to leave a comment below. Thanks for watching!

Top comments (0)