# MERNKIT

Welcome to mernkit! Focus on your features and customers. Let us handle the rest!

Thank you for checking out MERNKIT! As a SaaS founder with an exit I've learned that you must be obsessed with three things to be successful:&#x20;

1. Speed of execution
2. Customer Service
3. Solving the problem

Unfortunately, building a SaaS platform involves a lot of development that distracts you from obsessing on the things that matter. That is why I created MERNKIT. I needed a reusable  framework and tech stack that would allow me to:

1. Build and prototype SaaS products quickly
2. Focus on solving my customers problems

The documentation is split into two sections:

1. The back-end Node/Express/Mongo application&#x20;
2. The react/material-ui front-end.&#x20;

With all that being said, I hope you enjoy MERNKIT as much as I do! Happy coding!


# Features

Everything you need for a SaaS besides your core functionality

1. React Front-end
   1. Uses Material-UI for theme and reusable components and design system.&#x20;
   2. Functional Components and Hooks.
2. Authentication (Passport.js)&#x20;
   1. Google
   2. Facebook
   3. Traditional Username/Password (JWT)
   4. Password Reset
3. Subscription Management (Stripe)
   1. Trials
   2. Credit Card Payment
   3. Payment warnings/lockout&#x20;
   4. Subscribe/Unsubscribe
   5. Update Subscriptions
4. Tenant Management
   1. User Management
   2. Permission Management
   3. Tenant Management
5. Transactional Emails (Mailgun Templates)
   1. &#x20;Password Reset
   2. Email Confirmation
   3. User Invitations


# Tech Stack

* [MongoDB Atlas](https://www.mongodb.com/cloud/atlas)
* [Mongoose](https://mongoosejs.com/)
* [Express.js](https://expressjs.com/)
* [NodeJS](https://nodejs.org/en/)
* [React](https://reactjs.org/)
* [Material-UI](https://material-ui.com/)
* [Stripe](https://docs.mernkit.com/www.Stripe.com)
* [Mailgun](https://docs.mernkit.com/www.mailgun.com)

Please note this list is not exhaustive as there are a few other small packages uses for validation, etc. These are the heavy hitters.&#x20;


# Installation

Alright let's do this! First let's get your environment setup if it hasn't been already. Everything needed is free or has a free tier. We need to be scrappy in our early days! &#x20;

1. [Install NodeJS](https://docs.mernkit.com/www.nodejs.org)
2. Register for [MongoDB Atlas](https://www.mongodb.com/cloud/atlas) &#x20;
   1. Create a database called backend with the following collections:
      1. tenants
      2. users
   2. Create a user with access to the database.&#x20;
3. Register for [Stripe](https://docs.mernkit.com/www.Stripe.com)
4. Register for [Mailgun](https://docs.mernkit.com/www.mailgun.com)
5. Register for a [Facebook Developer Account](https://developers.facebook.com/) (used for authentication)
6. Register for a [Google Cloud Account](https://cloud.google.com/) (used for authentication)

We are now on our way!&#x20;

Open up your favorite shell (bash, cmd, etc), go into the backend directory, and type&#x20;

```
npm install
```

This will install all the other dependencies needed such as express, mongoose, etc. &#x20;

Now, go into the frontend directory and do the same.&#x20;

```
npm install
```

This will install all dependencies needed for the frontend such as, react-router, material-ui, validate.js, etc.&#x20;


# Application Structure

Below I will list the general API layout. I will not list all functions just a few to give you an understanding of what you will find in each file.&#x20;

* App.js (Entry Point)&#x20;
* nodemon.json (environmental variables used for debugging)
  * Controllers
    * stripe-controller.js (Stripe middleware functions)&#x20;
      * Get Plan Options &#x20;
      * Get Subscription Status...&#x20;
    * users-controller.js (User  middleware functions)&#x20;
      * Get Users
      * Get Permissions...
  * Middleware
    * passport.js&#x20;
      * Facebook Authentication Strategy
      * Google Authentication Strategy&#x20;
      * JWT Authentication Strategy...&#x20;
  * Models
    * http-error.js&#x20;
      * Wrapper for error responses.&#x20;
    * tenant.js
      * Mongoose Model for Tenants
    * users.js
      * Mongoose Model for Users
  * Routes
    * stripe-routes.js
      * routes to controller methods starting with /api/stripe
    * users-routes.js
      * routes to controller methods starting with /api/users
  * Shared
    * email.js
      * wrapper methods for mailgun transactional emails
    * helper.js
      * method to handle potential tenant name collisions
    * stripe.js
      * wrapper methods for strip operations
        * Cancel Subscription
        * Update Subscription...


# Environmental Variables

In designing MERNKIT I wanted the platform to be as plug and play as possible. Therefore, the setup is almost entirely managed by setting environmental variables. For development, you will edit the nodemon.json file. Depending on how you deploy your platform into production you will need to copy this information into a different area. I will share documentation on how to setup MERNKIT on AWS at the end of the section.&#x20;

Your nodemon.json file will contain the following empty variables that must be filled out. I will put descriptions where your variable value should go.&#x20;

* Callback values can be left as is provided you configure Google and Facebook with the same URLs.&#x20;
* FRONTEND\_URL value can also be left as is in the default configuration.&#x20;
* COOKIEDOMAIN should be left as localhost for testing. This should be set as the top level domain so the frontend has access to the cookie sent by the backend if you are using different subdomains for the frontend and backend. For example api.mernkit.com (backend) /app.mernkit.com (frontend)&#x20;

```
{
    "env": {
        "PROJECTNAME": "Your Product Name",  
        "DB_USER": "MongoDB Atlas USer",
        "DB_PWD": "MongoDB Atlas Password",
        "DB_NAME": "MongoDB Database Name",
        "KEY": "Encryption Key for JWT", 
        "FACEBOOK_CLIENT_ID":"Client ID for Facebook Auth",
        "FACEBOOK_CLIENT_SECRET":"Secret for Facebook Auth",
        "FACEBOOK_CALLBACK_URL":"/api/users/fb/cb", 
        "GOOGLE_CLIENT_ID":"Client ID for Google",
        "GOOGLE_CLIENT_SECRET": "Client Secret for Google",
        "GOOGLE_CALLBACK_URL": "/api/users/google/cb",
        "FRONTEND_URL":"http://localhost:3000",
        "MAILGUN_APIKEY": "Mailgun API Key",
        "MAILGUN_DOMAIN":"Mailgun domain (see Mailgun website)",
        "MAILGUN_FROM": "See mailgun website",
        "MAILGUN_TEMPLATE_SENDCONF": "Create Mailgun Template and place name here",
        "MAILGUN_TEMPLATE_PWRESET": "Same as above",
        "MAILGUN_TEMPLATE_ADDUSER": "Same as above",
        "COOKIEDOMAIN": "localhost", 
        "STRIPEID": "Stripe Private ID",
        "DEFAULTPRICE": "Default Price ID for trials",
        "TRIALPERIODDAYS": "Number of days you want your default trial to last"
        }
    }
```


# Google and Facebook Auth

In order to setup authentication with Google and Facebook, you need to create the keys noted in the environmental variables document. Instructions on how to do this can be found below. If you need help, don't hesitate to reach out!&#x20;

{% embed url="<https://developers.google.com/identity/sign-in/web/sign-in>" %}

{% embed url="<https://developers.facebook.com/docs/facebook-login/>" %}


# API

The structure of MERNKIT dictates that all routing is done by Routers in the routes folder.  All the authentication methods issue a JSON Web Token for continual API authentication. Therefore, Keep a close eye out for the following line:&#x20;

```
router.use(passport.authenticate("jwt", { session: false }));
```

**Anything above that line in a routes file is accessible without authentication.**&#x20;

**Anything below is protected.**&#x20;

When you create your own routes you can use this same line of code to protect your routes.&#x20;


# Deployment

I made MERNKIT to be as agnostic about the ultimate deployment environment as possible. Personally, I use AWS. A pretty good document on setting up an elastic beanstalk environment for MERNKIT can be found below:&#x20;

<https://medium.com/@xoor/deploying-a-node-js-app-to-aws-elastic-beanstalk-681fa88bac53>

&#x20;


# Application Structure

MERNKIT was scaffolded using "create-react-app". The frontend is based on the free Material-UI theme Devias Kit and leverages Material-UI components for fast prototyping with a consistent design scheme. Lazy loading is implemented where it makes sense. Folders are in CAPS.&#x20;

* SRC
  * Index.js (entry point).
  * App.js (Main App).&#x20;
  * Routes.js (Routes for MERNKIT)&#x20;
    * Routes are wrapped in either the "Minimal" or "Main" layouts.&#x20;
    * "Minimal" is used for pages that don't require navigation like login, signup, password reset, etc.&#x20;
  * .env (Environmental Variables for Development)
  * .env.production (Environmental Variables for Production)
    * THEME
      * Configuration for material-ui theme provider
    * &#x20;PAGES
      * Top level .js files are the containers for each view within MERNKIT.&#x20;
        * COMPONENTS
          * PAGENAME
            * Components that makeup pages that are not reusable.&#x20;
    * LAYOUT
      * Layout wrappers "Main" and "Minimal" for routes as described above.&#x20;
    * COMMON
      * CONTEXT
        * Authentication Context for managing authentication state throughout the app
      * HOOKS
        * alertbar-hook.js - used for tracking state for in app notifications
        * auth-hook.js - used for tracking authentication state within the auth-context.&#x20;
        * confirmemail-hook.js - tracks state for confirmation emails
        * form-hook.js - hook for form state
        * http-hook.js - wrapper for fetch API.&#x20;
        * permission-hook.js - hook to manage permission state.&#x20;
      * UI
        * Reusable UI components like AlertBar, ErrorModal, and LoadingSpinner.


# Environmental Variables

In designing MERNKIT I wanted the platform to be as plug and play as possible. Therefore, the setup is almost entirely managed by setting environmental variables. For development, you will edit the .env file. For production you will edit the .env.production file. I will share documentation on how to setup MERNKIT on AWS at the end of the section.&#x20;

Your .env file will contain the following empty variables that must be filled out. I will put descriptions where your variable value should go.&#x20;

```
REACT_APP_BACKEND_URL=http://localhost:5000
REACT_APP_COOKIEDOMAIN=localhost
REACT_APP_STRIPE=STRIPE PUBLIC KEY
```


# Deployment

I made MERNKIT to be as agnostic about the ultimate deployment environment as possible. Personally, I use AWS. A pretty good document on setting up an elastic beanstalk environment for MERNKIT can be found below:&#x20;

{% embed url="<https://medium.com/serverlessguru/deploy-reactjs-app-with-s3-static-hosting-f640cb49d7e6>" %}


# Other Resources

Reading through and referencing the Material-UI documentation will be extremely helpful in designing your front-end.&#x20;

{% embed url="<https://material-ui.com/getting-started/usage/>" %}

If you need to brush up on React, or your development skills in general I recommend the courses here:

{% embed url="<https://academind.com/>" %}


