A simple Node.js server built with Express and MongoDB, demonstrating JWT-based authentication.
- 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.
- Node.js installed
- MongoDB instance (local or cloud, e.g., MongoDB Atlas)
-
Clone the repository:
git clone https://github.com/deepakb/express-mongo-server.git cd express-mongo-server -
Install dependencies:
npm install
-
Open
src/server.js. -
Locate the
mongoURLvariable 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. -
(Optional) The JWT secret key is currently hardcoded as
'MY_SECRET_KEY'insrc/routes/userRoutes.jsandsrc/middleware/requireAuth.js. You may want to change this.
To start the development server with nodemon (auto-restarts on changes):
npm run devThe server will start on http://localhost:3000.
-
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": "..." }
- GET /
- Requires
Authorizationheader with Bearer token. - Header:
Authorization: Bearer <your_token> - Response:
"Hello there!"
- Requires
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.