How to Set Up a Django and React SaaS Boilerplate: A Step-by-Step Guide

rcmiskrcmisk
8 min read

Starting a Software as a Service (SaaS) project can be daunting, especially with the initial setup of the infrastructure. Luckily, with the right boilerplate, much of the groundwork is laid out for you. This guide will walk you through setting up a SaaS application using a specific Django backend and React frontend code, including integrating Stripe for payments, Postmark for emails, user management and authentication, Cloudinary for media file uploads, dynamically rendered landing page, blog creation through Django Admin, Google Analytics, Material UI, setting up a PostgreSQL database, and deploying to Render.com. Let's dive in!

Backend Setup

Initial Setup

  1. Create a Project Folder: Start by navigating to your Desktop or preferred directory in your terminal and create a folder named saas-boilerplate. Then, create a subdirectory named backend and navigate into it.

     cd Desktop
     mkdir saas-boilerplate
     cd saas-boilerplate
     mkdir backend
     cd backend
    
  2. Clone the Boilerplate Repository: Clone the backend boilerplate repository into your backend directory.

     git clone https://github.com/rcmiskin10/dj_react_saas_backend_render_template.git .
    
  3. Set Up a Virtual Environment: Use virtualenv to create an isolated Python environment. Activate it and install the project's dependencies.

     pip install virtualenv
     python3.8 -m venv env
     source env/bin/activate
     pip install -r requirements.txt
    
  4. Environmental Variables: Create a .env file in your backend directory. Populate it with the necessary environmental variables provided below:

    1.   STRIPE_API_TEST_PK=<STRIPE_API_TEST_PK>
        STRIPE_API_TEST_SK=<STRIPE_API_TEST_SK>
        STRIPE_LIVE_MODE=False
        PROD_BACKEND_URL=<PROD_BACKEND_URL>
        PROD_FRONTEND_URL=<PROD_FRONTEND_URL>
        BACKEND_URL=http://127.0.0.1
        FRONTEND_URL=http://localhost:3000
        DEBUG=True
        DEV_EMAIL_HOST_USER=<DEV_EMAIL_HOST_USER>
        DEV_EMAIL_HOST_PASSWORD=<DEV_EMAIL_HOST_PASSWORD>
        POSTMARK_SERVER_TOKEN=<POSTMARK_SERVER_TOKEN>
        DEFAULT_FROM_EMAIL=<DEFAULT_FROM_EMAIL>
      
  5. Now you need to set up Stripe.

    1. If you do not have a stripe account register a free one here: https://dashboard.stripe.com/register. If you do have a stripe account login here: https://dashboard.stripe.com/login.

    2. Once account is set up or you're logged in, turn on `Test Mode` (Toggle button in top right corner of dashboard) it should bring you to: https://dashboard.stripe.com/test/payments

    3. Go to https://dashboard.stripe.com/test/apikeys

      1. Grab your `Publishable key` token and set the environmental variable `STRIPE_API_TEST_PK` in your `.env` file created above.

      2. Next grab your `Secret key` token and set the environmental variable `STRIPE_API_TEST_SK` in your `.env` file created from above.

      3. Next go to Stripe Products to add your products, i.e. subscription tiers

        1. Add as many tiers as you want i.e.

          1. Free w/ a description and price: $0

          2. Pro w/ a description and price: say $10

          3. Make sure both are Recurring and Monthly or however you would like to set up your subscriptions.

  6. Postgres Database Setup: Download and install PostgreSQL. You can use this download link. Once installed, create a database named postgres and ensure your settings.py reflects the correct database settings. For example: default="postgresql://postgres:postgres@localhost/postgres", if your database name is postgres.

  7. Apply migrations and create a superuser for Django admin access.

     python manage.py migrate
     python manage.py createsuperuser
    
  8. Running the Server: Start your Django server and log into the admin panel to verify that everything is set up correctly.

     python manage.py runserver
    

Integrating Stripe Products and Prices, Email, and Landing Page data

  1. Add Products and Prices: Navigate to the Django admin payments section to add Stripe products and their prices. Ensure each product in Django matches its counterpart in Stripe, including the recurring intervals and price IDs.

    1. You can find Stripe Product Id in stripe products and click on product and in the URL you will see an ID with prefix prod_xxxxxxxx and letters and numbers as the unique id.

    2. Do the same for all products

    3. Now go to Django Admin Product Price

      1. Add the price for each product from Stripe here: Django Admin Add Product Link

      2. Select Product that you added to Django Admin.

      3. Add the Price from what you entered on Stripe. Add the interval, i.e. Monthly

      4. Add the stripe price id

        1. Go to https://dashboard.stripe.com/test/products?active=true

          1. Select the Product and scroll down to Pricing and look under API ID and copy id with prefix and numbers/letters like price_xxxxxxxxx and paste into stripe price id on django admin. 5. Do for all products
      5. Now you can add descriptions of the tiers here: Django Admin Add Product Description Link

        1. Add as many description list items for each product
  2. Email Setup: Configure your development email settings by adding DEV_EMAIL_HOST_USER and DEV_EMAIL_HOST_PASSWORD to your .env file, using an app password generated from your Gmail account.

    1. Set DEV_EMAIL_HOST_USER to your gmail for DEV testing

    2. Set your DEV_EMAIL_HOST_PASSWORD to the password set up in your gmail account from above. You need to create an App Password in: https://myaccount.google.com/security

      1. Make sure 2-Step Authentication is enabled.

      2. Then go to https://myaccount.google.com/apppasswords and create a new app and a new password will be created.

      3. Now Emails will be sent through gmail smtp in DEV

  3. Next up is setting up the landing page data.

    1. Note here you can add whatever copy, images, icons, you would like through the Django admin

      1. Go to http://127.0.0.1:8000/admin/landingpage/landingpage/add/

        1. Add the hero section copy and image

        2. Add the features of your SaaS

          1. the Feature mui icon name: can be selected from https://mui.com/material-ui/material-icons/?query i.e. find Add and get the name of the icon from the end of the import in the modal import AddIcon from '@mui/icons-material/Add'; i.e. Add

          2. You can add as many features as you like and Order them however you like by applying 1,2,3... to each feature. i.e. 1 will be first in line.

          3. Do the same for how it works, Secondary hero, and Social Media Links

  4. We will set up prod environmental variables later.

Frontend Setup

  1. Setting Up the Frontend: In a new terminal, navigate to your project root and set up the frontend directory by cloning the frontend boilerplate repository. Install dependencies with npm install.

     mkdir frontend
     cd frontend
     git clone https://github.com/rcmiskin10/dj_react_saas_frontend_render_template.git .
     npm install
    
  2. Configure Environment Variables: Create a .env file in your frontend directory. Add your Stripe Publishable key and Google Analytics ID.

    1. Add the publishable key from Stripe to the environmental variable REACT_APP_STRIPE_API_TEST_PK with the value from STRIPE_API_TEST_PK in backend/.env

    2. Now add an environmental variable REACT_APP_GA_ID for Google Analytics

      1. Go to https://analytics.google.com/

        1. Add an analytics account

        2. Add an app

        3. Go to top search bar and search for MEASUREMENT ID in Data Streams and copy the ID that has prefix G-XXXXXXXX 4. Past that G-XXXXXXXX as value for environmental variable REACT_APP_GA_ID in frontend/.env

  3. Start the Frontend Server: Run npm start to launch your React app. Your SaaS landing page should now be visible at http://localhost:3000/.

Deploying toRender.com

  1. Prepare for Deployment: Ensure your backend and frontend folders are pushed to separate GitHub repositories.

  2. Deploying the Backend: Follow Render.com's documentation to deploy your Django app, adding the necessary environment variables for production, including Stripe keys, Cloudinary for media files, and email settings via Postmark.

    1. Follow tutorial here: https://docs.render.com/deploy-django#use-renderyaml-for-deploys

      1. The backend/render.yaml already exists in the saas boilerplate. You can change all the names to fit whatever you like, but our boilerplate named everything backend

        1. In the Render Dashboard, go to the Blueprints page and click New Blueprint Instance.

          1. Make sure to first create a repository to hold your backend/ folder on github.

          2. Now you can select the repository that contains your blueprint and click Connect.

          3. Give your blueprint project a name and click Apply.

        2. Now add the Production Environmental Variables by clicking the backend app and going to Environment

          1. Add you Stripe STRIPE_API_TEST_PK found in your local .env file or if you are ready to use live Stripe data use the Production PK found in stripe dashboard.

          2. Same with the STRIPE_API_TEST_SK

          3. STRIPE_LIVE_MODE=False

          4. BACKEND_URL will be the url that your backend render app is pointing to: something similar to this backend-xxxxonrender.com

          5. For your media files first set up Cloudinary account by going to the cloudinary website and create a free cloudinary account. After your account has been created, go to the dashboard page and copy the cloud name, api key and api secret.

            1. Add the cloud name to CLOUDINARY_CLOUD_NAME

            2. Add the api key to CLOUDINARY_API_KEY

            3. Add the api secret to CLOUDINARY_API_SECRET

          6. For your emails create a postmark account here https://postmarkapp.com/. Follow instructions here: https://postmarkapp.com/support/article/1008-what-are-the-account-and-server-api-tokens to find your Server API Token and set it to POSTMARK_SERVER_TOKEN

            1. Set DEFAULT_FROM_EMAIL to your email with postmark.
          7. After you deploy the frontend app below, come back to setting FRONTEND_URL

          8. Finally run pythonmanage.pycreatesuperuser in the Render shell in the settings of the backend app so that you can create an admin account.

            1. To see your backend admin page, go to <YOUR_APP_URL>/admin to login.
  3. Deploying the Frontend: Deploy your React app on Render.com, setting environment variables for connecting to the backend API, Stripe, Cloudinary, and Google Analytics.

    1. Connect your github account here: https://dashboard.render.com/select-repo?type=static

      1. Follow the instructions to deploy

        1. Once deployed go to settings for frontend app

          1. In Redirect/Rewrite rules add:

            1. /* as Source

            2. /index.html as Destination

            3. And Rewrite as Action

          2. Now go to Environment and add:

            1. REACT_APP_STRIPE_API_TEST_PK to same Stripe API Key that you set in backend

            2. Add REACT_APP_BACKEND_API_URL and use the backend url from above after backend was deployed

            3. Add your REACT_APP_MEDIA_URL to the Cloudinary url. Something like this https://res.cloudinary.com/xxxxxxx/image/upload/v1/ The xxxxxxx should be found in your cloudinary dashboard that you used in backend set up.

            4. Now add REACT_APP_GA_ID from your .env REACT_APP_GA_ID in local file.

            5. Finally take the Frontend url from the react frontend app and set it in the backend app on render.com's environmental variable FRONTEND_URL that you previously set up.

  4. FinalAdjustments: After deploying both frontend and backend, ensure all environment variables are correctly set and pointing to the right services. Test your live application to ensure everything works seamlessly.

Congratulations! You've successfully set up and deployed your SaaS boilerplate application. This setup provides a solid foundation for developing your SaaS product, with scalable options for payment processing, database management, and deployment strategies. Happy coding!

Coming soon!

P.S comment below on any issues!

Sign up for my newsletter to hear about my #buildinpublic journey!

0
Subscribe to my newsletter

Read articles from rcmisk directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

rcmisk
rcmisk

Lover of coding, software development/engineering, indie hackers podcast/community, start-ups, music, guitar, technology, fitness, running, biking, learning new things, travel, the beach, and hiking/mountains. As a kid I had too many interests. I grew up playing soccer from an early age and played through college! Sports and being a part of a team was always part of my DNA. Not only did I value sports and competition but I loved music, art, drawing, animation, film, computers, math, and learning. Once I hit college, the decision to choose my life path was paralyzing, and ultimately led me down many different paths. I explored economics, finance, psychology, philosophy, statistics, communications, and marketing. I graduated with a finance degree and thought the data science, statistics, and the trends and patterns would be a fun career, however my first entry level job in the industry discouraged me to continue in the industry and to explore other paths. I always had an itch to build and start something on my own or with family. Growing up I started a lawn mowing business, shoveling business, lemonade stands, and small Wordpress websites. I loved the creativity of coming up with ideas on how to help people and make money at the same time. I realized I loved technology, and seeing what could be created and started with technology really urged me to start down the path of learning how to code. My brother and I had an idea for a college social network (similar to Facebook), geared solely towards education and only for students at your college. We wanted to give students the ability to meet people on campus, finding work, organize course material, share notes and materials, find extracurricular activities, sell textbooks and furniture. I took it upon myself to learn how to build something like that. Basically taking an idea and making it happen. I learned about software development, coding languages, web frameworks, startups, marketing all on my own. I took online free courses, watched videos and tutorials about Django, Python, Javascript, HTML, and databases. I absolutely loved everything about the process. Seeing my work come to life and seeing people use what I created. It satisfied everything that I enjoyed growing up. The creativity, the design, artwork, coming up with a business, learning new things at my own pace, however I learned best, and working with my brother. I did all this while working full-time at a financial institution during my nights and weekends. We finally launched StudentGrounds, however after a year and 200 user signups later it slowly died down. This experience of taking an idea and learning everything needed to make it a reality basically propelled my interest in learning how to code and do that full time. I learned all about computer science, taking a certificate course at night at a local university. I started another project idea on the side for an event management application for my father's youth soccer tournament, and started applying to every technology company I could think of. I ultimately got my first software engineer job at a small start up in Boston as an apprentice/intern and learned on the job before getting my first full-time software engineer position at a large Boston e-commerce company. My goal there was to learn as much as I could from season professionals, and learning how the corporate world works in terms of software development. My ultimate goal is to create something on my own doing something I love, as well as enjoy life, and give back to others through education. Right now I am a full-time Software Engineer with 6 years in the marketing tech space, trying to finish a SaaS boilerplate so that I can spin up any web application for any idea at the click of a button, which will then set me up for my next idea, IdeaVerify, an automated way to verify/validate you're SaaS application idea before actually starting to code and wasting many hours and years developing something that no one would use. This blog is about my journey navigating the software engineering world, without a CS degree, building in public, keeping record of what I learned, sharing my learnings and at the same time giving back to others, teaching them how to code and giving helpful hints and insights. I am also using this blog to showcase other sides of me such as art, music, writing, creative endeavors, opinions, tutorials, travel, things I recently learned and anything else that interests me. Hope you enjoy!