Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

With vercel #68

Merged
merged 8 commits into from
Apr 16, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,119 @@
---
title: How to deploy SuperTokens with React and NodeJS on Vercel
date: "2022-04-14"
description: "This tutorial wil guide you on how to add SuperTokens to a React and Express app deployed on Vercel"
cover: "vercel.png"
category: "programming"
author: "SuperTokens Team"
---

Have you ever considered implementing easy and safe authentication on your web application at no cost? Have you considered integrating authentication with minimal or no initial environment setup? Then hang on for the next 10 minutes.

In this tutorial, you’ll learn how to add SuperTokens authentication to your React and NodeJS application and deploy it on Vercel.

## What is SuperTokens

[SuperTokens](https://supertokens.com) is a developer first, open-source, flexible alternative to Firebase, AWS Cognito, and Auth0. SuperTokens allow you to add secure authentication to your web application in minutes with a prebuilt UI that you can easily customize.

## Why use SuperTokens

SuperTokens has lots of amazing features:

* **Pre-built UI**: SuperTokens has pre-built Sign up / sign-in forms (via our frontend SDK) that can be embedded on your website natively.
* **Feature segmentation:** With SuperTokens, you can pick only the features you need and see docs relevant to your use case (we call it "recipes")
* **Priced for startups:** SuperTokens has a generous limit and pricing for our managed service, and it's free for self-hosted.
* **Integrate with any service:** You can set up your own content delivery service (e.g., SMS or email).
* **Secure**: Aside from login security, SuperTokens provides out of the box session security using `HttpOnly` cookies and `anti-CSRF` tokens. It also implements advanced token rotation techniques to detect against session hijacking.

## What is Vercel

Vercel is a platform for frontend frameworks and static sites that can be integrated with your headless content, commerce, or database. It offers a frictionless developer experience to handle the difficult tasks of deploying instantaneously, scaling automatically, and presenting tailored content globally. It's built for the frontend experience; create hybrid frontends using tools like Next.js, create lightweight event-driven APIs, and deploy to our Global Edge Network.

## Getting started

To get started with SuperTokens, please visit the [Recipe Guides page](https://supertokens.com/docs/guides) and pick the login method you want for your application. After choosing a guide, follow the quick setup section or one of the sections for integrating with a framework that you have chosen.

We also have a blog post for how to integrate [email password + social login with express and react](https://supertokens.com/blog/how-to-set-up-social-and-email-password-login-with-reactjs), if that is what you are looking for.


## Restructuring your application for Vercel deployment
Once you have done the basic implementation on your local system, we want to do the following to convert your application so that it can be deployed on Vercel:

1. Create an `api` folder. This folder will contain the API logic that we can deploy on Vercel. We will be exposing the API's entry point via an `index.js` file in this folder.
2. Open the `index.js` and export `app` at the end of the file as shown below

```js
module.exports = app;

```

> Note: We are deploying our backend as a standalone express app, and not with `/pages/api` serverless functions that Vercel provides. If you want to deploy using `/pages/api`, then you can check out our nextJS framework integration guide that's within the recipe guide.

## Change the appInfo config to get Vercel deployments to work

To enable your project to run on production and the inspect sites for Vercel, you need to make the `websiteDomain` and `appDomain` point to the URLs generated by Vercel. The production URL is always the same for an app, but the inspect URL keeps changing. To allow it to work in this dynamic condition, we must set the values of `apiDomain` and `websiteDomain` dynamically.

### On the backend

```js
appInfo: {
appName: "My App",
apiDomain: 'process.env.VERCEL_URL',
websiteDomain: 'process.env.VERCEL_URL',
apiBasePath: "/api/auth",
websiteBasePath: "/auth",
},
```

Vercel provides an env var - `process.env.VERCEL_URL` - to the backend which is equal to the inspect URL / production URL (depending on the site that’s loaded). So we use this to set the `apiDomain` and `websiteDomain` values dynamically.

### On the frontend

We can use `window.location.origin` to get the currently loaded URL and set those to the `apiDomain` and `websiteDomain`. This way, even if the inspect URL keeps on changing, it will still point to the current domain.

```js
appInfo: {
appName: "TodoApp",
apiDomain: window.location.origin,
websiteDomain: window.location.origin,
apiBasePath: "/api/auth",
websiteBasePath: "/auth",
},

```

> This only works if the frontend and backend of your application have the same domain. If your backend is hosted elsewhere and you use Vercel only for the frontend, be sure to change the `apiDomain` on the frontend and backend to point to your backend server. In this case however, your app may not function properly for inspect deployments since your backend server has no way of knowing what the inspect URL of the frontend site would be on each deployment.

## Update the CORS Middleware

You also need to update the CORS middleware origin with the `VERCEL_URL` environment variable.

```js
app.use(
cors({
origin: process.env.VERCEL_URL,
allowedHeaders: ['content-type', ...SuperTokens.getAllCORSHeaders()],credentials: true,
})
);
```

## Configure Vercel and Deploy

With the backend and frontend of your application code updated, create a `vercel.json` file in the root directory of your application which will instruct Vercel to push all traffic on `/api/*` path to our our express backend server:

```js
{
"rewrites": [{ "source": "/api/(.*)", "destination": "/api" }]
}
```

Finally, to deploy the app to Vercel, you need to run the vercel command on the root of your project:

```sh
vercel
```

Once deployed, you should be able to test the login functionality on the inspect URL and the production URL.

## Demo app
We also have [a demo app on our GitHub](https://github.com/supertokens/supertokens-auth-react/tree/master/examples/with-emailpassword-vercel) that has Email Password login with express and React, and is configured to work with Vercel. You can even see its [live preview](https://with-emailpassword-vercel-beryl.vercel.app/).
Binary file added static/covers/vercel.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.