import React from 'react';
import { BrowserRouter as Router, Route, Switch } from 'react-router-dom';
import Login from './Login';
import Register from './Register';
import Posts from './Posts';
function App() {
return (
<Router>
<Switch>
<Route path="/login" component={Login} />
<Route path="/register" component={Register} />
<Route path="/posts" component={Posts} />
</Switch>
</Router>
);
}
export default App;
5. Setup proxy for the client:
In client/package.json, add:
"proxy": "http://localhost:5000"
Running the Application:
Start the backend:
node server.js
Start the frontend:
cd client
npm start
This is a basic MERN stack application with JWT authentication. You can register a user, log in, and access a protected resource. Remember to handle errors and edge cases in a real-world application.
Enhancements and Best Practices:
Backend:
Error Handling: Implement a global error handler using middleware to catch and handle all errors.
Error Handling: Handle API errors gracefully. Show user-friendly error messages.
Loading States: Show a spinner or a loading message while fetching data.
Logout: Implement a logout feature that clears the JWT token from local storage.
Token Expiry: Handle JWT token expiry. If a token is expired, prompt the user to log in again.
HTTPS: Always use HTTPS in production to ensure the JWT token is transmitted securely.
Refresh Tokens: Implement refresh tokens to get a new access token without asking the user to log in again.
Styling: Use libraries like styled-components or frameworks like Bootstrap or Material-UI to improve the UI.
Testing: Write unit and integration tests using libraries like Jest and React Testing Library.
Conclusion:
This guide provides a basic understanding of setting up JWT authentication in a MERN stack application. However, when building a real-world application, always consider security best practices, handle edge cases, and test thoroughly.
This will be a basic app where users can register, log in, and view a protected resource using JWT for authentication.
Backend Setup:
1. Initialize a new Node.js project:
2. Install necessary packages:
3. Setup MongoDB:
4. Create a
.env
file for environment variables:5. Setup Express and MongoDB:
server.js
:6. Create User model:
models/User.js
:7. Create routes for registration and login:
routes/auth.js
:8. Add routes to
server.js
:9. Create middleware to verify JWT:
middleware/verifyToken.js
:10. Create a protected route:
routes/posts.js
:Add this route to
server.js
:Frontend Setup:
1. Create a new React app:
2. Create a Login and Register component:
Login.js
:Register.js
:3. Create a component to display the protected resource:
Posts.js
:4. Add components to
App.js
and setuprouting:
Install react-router-dom:
App.js
:5. Setup proxy for the client:
In
client/package.json
, add:Running the Application:
Start the backend:
Start the frontend:
This is a basic MERN stack application with JWT authentication. You can register a user, log in, and access a protected resource. Remember to handle errors and edge cases in a real-world application.
Enhancements and Best Practices:
Backend:
Rate Limiting: Use packages like
express-rate-limit
to prevent brute-force attacks.Logging: Use
morgan
orwinston
for logging requests and errors.Validation: Use
express-validator
orjoi
to validate user input.Frontend:
State Management: Consider using
Redux
orContext API
for state management, especially when your app grows.Protected Routes: Use a higher-order component or a custom route to protect frontend routes.
Usage:
Error Handling: Handle API errors gracefully. Show user-friendly error messages.
Loading States: Show a spinner or a loading message while fetching data.
Logout: Implement a logout feature that clears the JWT token from local storage.
Token Expiry: Handle JWT token expiry. If a token is expired, prompt the user to log in again.
HTTPS: Always use HTTPS in production to ensure the JWT token is transmitted securely.
Refresh Tokens: Implement refresh tokens to get a new access token without asking the user to log in again.
Styling: Use libraries like
styled-components
or frameworks likeBootstrap
orMaterial-UI
to improve the UI.Testing: Write unit and integration tests using libraries like
Jest
andReact Testing Library
.Conclusion:
This guide provides a basic understanding of setting up JWT authentication in a MERN stack application. However, when building a real-world application, always consider security best practices, handle edge cases, and test thoroughly.
Originally posted by @akash-coded in https://github.com/akash-coded/mern/discussions/199