


Authentication with JWT on Frontend and Backend: Implementing with Node.js and ReactJS (in TypeScript)
Authentication via JSON Web Token (JWT) is widely used to secure APIs and ensure that only authorized users can access certain data. In this post, we will show you how to configure JWT on the backend with Node.js and on the frontend with ReactJS using TypeScript, from token generation to secure user session management.
Configuring the Backend with Node.js
First, let's create an API with Node.js, Express and TypeScript that generates and validates JWT tokens.
Step 1: Configuring the Environment
Create a new project and install the main dependencies:
npm init -y npm install express jsonwebtoken bcryptjs dotenv npm install -D typescript @types/node @types/express @types/jsonwebtoken @types/bcryptjs ts-node
Create a tsconfig.json file for TypeScript configuration:
{ "compilerOptions": { "target": "es6", "module": "commonjs", "outDir": "./dist", "strict": true, "esModuleInterop": true }, "include": ["src/**/*.ts"], "exclude": ["node_modules"] }
Step 2: Structuring the Backend
Create a simple structure, starting with a server.ts file and a routes folder to organize authentication routes.
server.ts
import express, { Application } from 'express'; import dotenv from 'dotenv'; import authRoutes from './routes/authRoutes'; dotenv.config(); const app: Application = express(); app.use(express.json()); app.use('/api/auth', authRoutes); const PORT = process.env.PORT || 5000; app.listen(PORT, () => console.log(`Servidor rodando na porta ${PORT}`));
routes/authRoutes.ts
Create a file for authentication routes. Here we will have a login route that will validate the user and return the JWT token.
import express, { Request, Response } from 'express'; import jwt from 'jsonwebtoken'; import bcrypt from 'bcryptjs'; const router = express.Router(); // Simulação de banco de dados const users = [{ username: 'usuario', password: 'senha123' }]; router.post('/login', async (req: Request, res: Response) => { const { username, password } = req.body; const user = users.find(u => u.username === username); if (!user || !(await bcrypt.compare(password, user.password))) { return res.status(401).json({ message: 'Credenciais inválidas' }); } const token = jwt.sign({ username }, process.env.JWT_SECRET as string, { expiresIn: '1h' }); res.json({ token }); }); export default router;
Step 3: Securing Routes with Middleware
Add middleware to protect routes that require authentication.
middleware/authMiddleware.ts
import { Request, Response, NextFunction } from 'express'; import jwt from 'jsonwebtoken'; interface JwtPayload { username: string; } export const authMiddleware = (req: Request, res: Response, next: NextFunction): void => { const token = req.headers['authorization']; if (!token) { res.status(403).json({ message: 'Token não fornecido' }); return; } jwt.verify(token, process.env.JWT_SECRET as string, (err, decoded) => { if (err) { res.status(401).json({ message: 'Token inválido' }); return; } req.user = decoded as JwtPayload; next(); }); };
Configuring the Frontend with ReactJS
On the frontend, we will use React to handle authentication, sending credentials, and storing the JWT token.
Step 1: Configuring the Login Interface
First, create a Login.tsx component to capture the user's credentials and send a login request to the backend.
Login.tsx
import React, { useState } from 'react'; import axios from 'axios'; const Login: React.FC = () => { const [username, setUsername] = useState<string>(''); const [password, setPassword] = useState<string>(''); const [error, setError] = useState<string>(''); const handleLogin = async (e: React.FormEvent) => { e.preventDefault(); try { const response = await axios.post('/api/auth/login', { username, password }); localStorage.setItem('token', response.data.token); window.location.href = '/dashboard'; } catch (err) { setError('Credenciais inválidas'); } }; return ( <form onSubmit={handleLogin}> <input type="text" placeholder="Username" value={username} onChange={(e) => setUsername(e.target.value)} /> <input type="password" placeholder="Password" value={password} onChange={(e) => setPassword(e.target.value)} /> <button type="submit">Login</button> {error && <p>{error}</p>} </form> ); }; export default Login;
Step 2: Protect Routes in the Frontend
Create a function for protected routes, using the JWT token to access the API.
PrivateRoute.tsx
import React from 'react'; import { Route, Redirect, RouteProps } from 'react-router-dom'; interface PrivateRouteProps extends RouteProps { component: React.ComponentType<any>; } const PrivateRoute: React.FC<PrivateRouteProps> = ({ component: Component, ...rest }) => ( <Route {...rest} render={(props) => localStorage.getItem('token') ? ( <Component {...props} /> ) : ( <Redirect to="/login" /> ) } /> ); export default PrivateRoute;
Step 3: Send the JWT Token in Requests
Configure axios to automatically include the JWT token in protected requests.
axiosConfig.ts
import axios from 'axios'; const token = localStorage.getItem('token'); if (token) { axios.defaults.headers.common['Authorization'] = token; } export default axios;
Step 4: Example of Usage with a Protected Route
Now, create an example of a protected page that requires the token to access.
Dashboard.tsx
import React, { useEffect, useState } from 'react'; import axios from './axiosConfig'; const Dashboard: React.FC = () => { const [data, setData] = useState<string>(''); useEffect(() => { const fetchData = async () => { try { const response = await axios.get('/api/protected'); setData(response.data.message); } catch (error) { console.error(error); } }; fetchData(); }, []); return <h1>{data || 'Carregando...'}</h1>; }; export default Dashboard;
Conclusion
With these steps, we set up full JWT authentication in TypeScript for a project that uses Node.js on the backend and React on the frontend. This approach is highly secure, efficient and widely adopted to protect modern applications.
The above is the detailed content of Authentication with JWT on Frontend and Backend: Implementing with Node.js and ReactJS (in TypeScript). For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics











JavaScript is the cornerstone of modern web development, and its main functions include event-driven programming, dynamic content generation and asynchronous programming. 1) Event-driven programming allows web pages to change dynamically according to user operations. 2) Dynamic content generation allows page content to be adjusted according to conditions. 3) Asynchronous programming ensures that the user interface is not blocked. JavaScript is widely used in web interaction, single-page application and server-side development, greatly improving the flexibility of user experience and cross-platform development.

The latest trends in JavaScript include the rise of TypeScript, the popularity of modern frameworks and libraries, and the application of WebAssembly. Future prospects cover more powerful type systems, the development of server-side JavaScript, the expansion of artificial intelligence and machine learning, and the potential of IoT and edge computing.

Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

JavaScript is the core language of modern web development and is widely used for its diversity and flexibility. 1) Front-end development: build dynamic web pages and single-page applications through DOM operations and modern frameworks (such as React, Vue.js, Angular). 2) Server-side development: Node.js uses a non-blocking I/O model to handle high concurrency and real-time applications. 3) Mobile and desktop application development: cross-platform development is realized through ReactNative and Electron to improve development efficiency.

This article demonstrates frontend integration with a backend secured by Permit, building a functional EdTech SaaS application using Next.js. The frontend fetches user permissions to control UI visibility and ensures API requests adhere to role-base

I built a functional multi-tenant SaaS application (an EdTech app) with your everyday tech tool and you can do the same. First, what’s a multi-tenant SaaS application? Multi-tenant SaaS applications let you serve multiple customers from a sing

The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.
