Coder Social home page Coder Social logo

danielturus / react-express-jwt Goto Github PK

View Code? Open in Web Editor NEW

This project forked from philuchansky/react-express-jwt

0.0 1.0 0.0 486 KB

Example NodeJS, Express, Mongoose, React app with JWT auth for beginners WITHOUT redux.

HTML 11.44% JavaScript 87.86% CSS 0.70%

react-express-jwt's Introduction

React Application with JWT Authentication

Overview

This is an example application that serves an ExpressJS JSON api to a React client application. The React application is configured for a basic JWT authentication flow WITHOUT using redux. Great for those of you that are somewhat familiar with Node, Express, and Mongoose, but want to see an implementation of React + React Router with JWT authentication.

The React client app could easily be restructured to keep current user information in a Redux Store. Give it a shot!

Installation + Development

  1. git clone this repository to your local machine.

  2. run npm install from the cloned repo directory.

  3. create a .env file at the root of the application, adjacent to server.js.

    The only environment variable you have to declare in development is JWT_SECRET

    In the .env file, you can declare the following environment variables: JWT_SECRET, MONGODB_URI, and PORT. For example:

    JWT_SECRET=BOOOOOOOOOOOOOM
    MONGODB_URI=mongodb://localhost/react-express-jwt
    PORT=3001
    
  4. It's recommended that you run the api server on port 3001 while developing locally, as the client app will default to port 3000.

  5. Make sure mongod is running by running… ahem… mongod

  6. From that point you can run the api server either by using nodemon or just running node server.js

  7. Now for the client application. cd client

  8. Install the client app's dependencies with npm install

  9. From the client directory, run npm start to boot up the client application.

  10. $$$ Profit

Usage

It's common to identify the user making an authenticated request on the server side. In this application, the verifyToken middleware (declared in /serverAuth.js) decodes a provided token, and makes sure the request is coming from a valid user. When the user is validated, it is added to the req object as req.user.

Here's an example of how you can access the 'current user' from the server side app, assuming a user is logged in and sending an authenticated request:

const express = require('express')
const mySpecialRouter = new express.Router()

// JWT AUTH MIDDLEWARE:
const { verifyToken }  = require('../serverAuth.js')

const Comment = require('../models/Comment.js')

// all routes declared after this middleware require a token
mySpecialRouter.use(verifyToken)
mySpecialRouter.post("/comments", (req, res) => {
  // since this route succeeds 'verifyToken', it has the current user in req.user
  // so we can easily associate new mongo documents to the current user:
  Comment.create({ ...req.body, user: req.user }, (err, comment) => {
    if(err) return console.log(err)
    res.json({ success: true, message: "Comment created.", comment })
  })
})

module.exports = mySpecialRouter

Technologies

  • NodeJS + Express + Mongoose on the back
  • React client application on the front
  • React Router 4.*
  • Milligram CSS so it doesn't look like garbage
  • JSON Web Token authentication flow

Important Notes

  • While the Mongoose user schema enforces email uniqueness, there's no handler for duplicate user emails on the client side. (A user wouldn't know why they couldn't create their account if they came across this scenario).

react-express-jwt's People

Contributors

philuchansky avatar

Watchers

James Cloos avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.