I'm a Fullstack Developer that loves to code and build my ideas big or small. I write about what I learned and my experiences and some tips that are helpful.
In this tutorial, we will go through how to create a JWT authentication system using Node.js, Express.js, and PostgreSQL. Let's get started.
To get started, create a folder where you want to store your project. Open the folder in your favorite code editor. I will be using VS Code.
In the terminal, run the following command to create a package.json file.
npm init -y
This will create a package.json file in your project folder. The -y flag will accept all the default values.
We will be using the following dependencies in this tutorial.
npm install express pg jsonwebtoken bcryptjs cors dotenv
create a file named app.js and add the following code.
In the terminal, run the following command to start the server.
node app.js
Open your browser and go to http://localhost:8000. You should see Hello world.
We will be using ElephantSQL to create our database. Create an account on ElephantSQL and create a new database.
open up pgAdmin and connect to your database. Then create a new table named users. The table should have the following columns.
Create a file named db.js in the root folder and add the following code. You can get your database connection string from ElephantSQL.
In the app.js file, add the following code.
then run the following command in the terminal.
node app.js
You should see Connected to database in the terminal and Server is running on port 5000.
Create a folder named routes and create a file named auth.js. Add the following code.
In the auth.js file, add the following code.
Create a folder named controllers and create a file named auth.js. Add the following code.
Also, add the following code to the auth.js file.
Then verify the user in the auth.js file.
Now lets update our app.js file, add the following code.
In the terminal, run the following command to start the server.
node app.js
Open Postman and send a POST request with name, username, password in the body to http://localhost:5000/auth/register. You should see the following response.
{
"auth": true,
"token": "Bearer [token]"
}
Open Postman and send a POST request with username, password, and the token from above in the body to http://localhost:5000/auth/login. You should see the following response.
{
"auth": true,
"token": "Bearer [token]"
}
You have successfully created a login and register system using Node.js, Express, and PostgreSQL.
In this tutorial, we created a simple authentication system using Node.js, Express, and PostgreSQL. We used JWT for authentication and bcrypt for hashing passwords.