Member-only story
Build a Rails API With JWT
Set up your user auth using JavaScript Web Tokens for improved security
This is a guide on creating and setting up a Rails API application from scratch.
The focus will be on user login and sign up and authorizing/authenticating them with JWT (JSON Web Tokens). Keep in mind that this approach represents one of many. Let’s begin with the setup.
Setup
Let’s generate a Rails API. From the terminal, run the following command:
rails new jwt-rails-api-app --database=postgresql --api
The flag --database=postgresql
is included to indicate that PostgreSQL is to be utilized as the database instead of SQLite, and the flag --api
is included to indicate that this application is to be set up as an API and to avoid generating the views and view helpers since they are not necessary for an API.
Open the newly generated folder and open Gemfile
. We need to include a few gems as part of the setup.
The first is to uncomment/include:
gem 'bcrypt'
Bcrypt will manage hashing the passwords for the user.
The second is to uncomment/include:
gem 'rack-cors'
This allows the Cross-Origin Resource Sharing (CORS) in the API. CORS prevents API calls from unknown origins.
And finally, include:
gem 'jwt'
From the terminal, run bundle install
to install the three gems in the application.
Next, navigate to config/initializers/cors.rb
and uncomment the following and also replace “example.com” with an asterisk.

Now, navigate to config/routes.rb
. We will define the routes accessible for this application.
For this guide, we will only focus on the routes that handle login, signing up a user, and auto-login. We will define a couple of custom routes to handle the login and auto-login.