Skip to content

deepakb/express-mongo-server

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

5 Commits
 
 
 
 
 
 
 
 

Repository files navigation

Express Mongo Auth Server

A simple Node.js server built with Express and MongoDB, demonstrating JWT-based authentication.

Features

  • User Authentication: Sign up and Sign in functionality.
  • JWT Protection: Secure routes using JSON Web Tokens.
  • MongoDB Integration: Uses Mongoose for object modeling.
  • Password Hashing: Uses bcrypt for secure password storage.

Prerequisites

  • Node.js installed
  • MongoDB instance (local or cloud, e.g., MongoDB Atlas)

Installation

  1. Clone the repository:

    git clone https://github.com/deepakb/express-mongo-server.git
    cd express-mongo-server
  2. Install dependencies:

    npm install

Configuration

  1. Open src/server.js.

  2. Locate the mongoURL variable and add your MongoDB connection string:

    const mongoURL = 'YOUR_MONGODB_CONNECTION_STRING';

    Note: For a production app, use environment variables (e.g., dotenv) to store secrets like the Mongo URL and JWT secret.

  3. (Optional) The JWT secret key is currently hardcoded as 'MY_SECRET_KEY' in src/routes/userRoutes.js and src/middleware/requireAuth.js. You may want to change this.

Running the Server

To start the development server with nodemon (auto-restarts on changes):

npm run dev

The server will start on http://localhost:3000.

API Endpoints

Auth

  • POST /signup

    • Creates a new user.
    • Body: { "email": "[email protected]", "password": "password", "firstName": "John", "lastName": "Doe" }
    • Response: { "token": "..." }
  • POST /signin

    • Authenticates an existing user.
    • Body: { "email": "[email protected]", "password": "password" }
    • Response: { "token": "..." }

Protected Routes

  • GET /
    • Requires Authorization header with Bearer token.
    • Header: Authorization: Bearer <your_token>
    • Response: "Hello there!"

Project Structure

  • src/server.js: Entry point of the application.
  • src/models/User.js: Mongoose model for User.
  • src/routes/userRoutes.js: Auth routes (signup, signin).
  • src/middleware/requireAuth.js: Middleware to protect routes.

About

A simple Node.js server built with Express and MongoDB, demonstrating JWT-based authentication.

Topics

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published