Production-ready HTTP client with JWT authentication for React
Documentation • NPM Package • GitHub • Report Bug
- Installation
- Quick Start
- Using CRUD Operations
- Route Protection
- When to Use
- Works well with
- Key Features
- Contributing
- Code of Conduct
- Author and Developers
- License
@forgepack/request is a complete, opinionated HTTP client built on top of the native Fetch API for React applications. It provides automatic JWT authentication, request/response interceptors, React hooks for state management, and standardized CRUD operations—everything you need to handle API communication in modern React apps.
Perfect for: Teams building React applications with JWT-based backends who want a plug-and-play solution that handles authentication, authorization, and API requests with minimal boilerplate.
# npm
npm install @forgepack/request
# yarn
yarn add @forgepack/request
# pnpm
pnpm add @forgepack/requestMake sure you have these installed:
{
"react": ">=16.8.0",
"react-dom": ">=16.8.0",
"react-router-dom": ">=6.0.0" // Optional, only if using RequireAuth
}// src/api.ts
import { createApiClient } from "@forgepack/request"
export const api = createApiClient({
baseURL: "https://api.service.com",
/** Called on 401 errors (expired token) */
onUnauthorized: () => window.location.href = "/login",
/** Called on 403 errors (without permission) */
onForbidden: () => window.location.href = "/notAllowed"
})// src/App.tsx
import React from 'react'
import { BrowserRouter } from 'react-router-dom'
import { AuthProvider } from '@forgepack/request'
import { api } from './api'
import { AppRoutes } from './routes'
function App() {
return (
<BrowserRouter>
<AuthProvider api={api}>
<AppRoutes />
</AuthProvider>
</BrowserRouter>
)
}
export default Appimport { useAuth } from '@forgepack/request'
import { useNavigate } from 'react-router-dom'
function LoginPage() {
const { loginUser } = useAuth()
const navigate = useNavigate()
const handleLogin = async (credentials) => {
const result = await loginUser(credentials)
if (result.success) {
navigate('/dashboard')
} else {
console.error('Login failed:', result.errors)
}
}
return (
<div>
{/* Your login form here */}
</div>
)
}import { create, retrieve, update, remove } from '@forgepack/request'
import { api } from './api/client'
// Create
const newUser = await create(api, 'users', {
name: 'John Snow',
email: 'john@example.com'
})
// Retrieve all
const allUsers = await retrieve(api, 'users')
// Retrieve paginated
const page = await retrieve(api, 'users', { page: 0, size: 10 })
// Update
const updated = await update(api, 'users', {
id: 1,
name: 'John Smith'
})
// Delete
await remove(api, 'users', '1')import { RequireAuth } from '@forgepack/request'
import { Route, Routes } from 'react-router-dom'
function App() {
return (
<Routes>
{/* Public routes */}
<Route path="/login" element={<LoginPage />} />
{/* Protected routes - any authenticated user */}
<Route path="/dashboard" element={<RequireAuth allowedRoles={['USER', 'ADMIN']}><Dashboard /></RequireAuth>} />
{/* Admin-only routes */}
<Route path="/admin" element={<RequireAuth allowedRoles={['ADMIN']}><AdminPanel /></RequireAuth>} />
</Routes>
)
}import { getToken, getPayload, isValidToken } from '@forgepack/request'
/** Check if token is valid */
if (isValidToken()) {
console.log('User is authenticated')
}
/** Get token data */
const auth = getToken()
console.log(auth.accessToken)
console.log(auth.role)
/** Decode payload */
const payload = getPayload()
console.log('User ID:', payload.sub)
console.log('Expires at:', new Date(payload.exp * 1000))- ✅ React applications (16.8+)
- ✅ JWT-based authentication
- ✅ RESTful APIs
- ✅ Applications requiring role-based access control
- ✅ Projects that need standardized CRUD operations
- ✅ Teams wanting to reduce authentication boilerplate
- ❌ GraphQL APIs (use Apollo Client instead)
- ❌ Non-JWT authentication (OAuth2, session-based, etc.)
- ❌ Server-side rendering with Next.js (token management relies on localStorage)
- ❌ React Native (localStorage not available)
Complete your React stack with other @forgepack packages:
| Package | Description |
|---|---|
| @forgepack/auth-jwt | Backend JWT authentication utilities |
| @forgepack/crud | Advanced CRUD components with forms |
| @forgepack/layout | Responsive layout components |
| @forgepack/modal | Modal dialogs for CRUD operations |
| @forgepack/datatable | Data tables with pagination and sorting |
- 🔐 Autenticação JWT - Automatic login with interceptors
- 🛡️ Route Protection - Role-based
RequireAuthcomponent - 📊 Request Hook -
useRequestwith pagination and search - ⚡ CRUD Operations - Ready-to-use functions for create, read, update, delete.
- 🔑 Token Management - Automatic validation and decoding
- 📱 Responsive - Loading, error, and pagination states
For detailed examples, usage guides, and API references, please visit: Complete Documentation
We welcome contributions! Please see our Contributing Guide for details.
# Clone repository
git clone https://github.com/forgepack/request.git
cd request
# Install dependencies
npm install
# Run tests
npm test
# Build
npm run buildPlease read our Code of Conduct before contributing.
- GitHub: Gadelha TI
- Website: forgepack.dev
This project is licensed under the MIT License - see the MIT LICENSE file for details.
MIT License
Copyright (c) 2024 Gadelha TI
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
⭐ Did you like the project? Leave a star! ⭐
Made with ❤️ by the Forgepack team
Documentation • NPM • GitHub • Issues