Opinionated Fetch-based HTTP client for React applications with JWT support, interceptors, and API request standardization.
npm install @forgepack/request@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.
bash
npm
npm install @forgepack/request
yarn
yarn add @forgepack/request
pnpm
pnpm add @forgepack/request
`
$3
Make sure you have these installed:
`json
{
"react": ">=16.8.0",
"react-dom": ">=16.8.0",
"react-router-dom": ">=6.0.0" // Optional, only if using RequireAuth
}
`
Quick Start
$3
`ts
// 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"
})
`
$3
`tsx
// 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 (
)
}
export default App
`
$3
`typescript
import { 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 (
{/ Your login form here /}
)
}
`
Using CRUD Operations
`typescript
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')
`
Route Protection
`typescript
import { RequireAuth } from '@forgepack/request'
import { Route, Routes } from 'react-router-dom'
function App() {
return (
{/ Public routes /}
} />
{/ Protected routes - any authenticated user /}
} />
{/ Admin-only routes /}
} />
)
}
`
$3
`typescript
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))
`
When to Use
$3
- ✅ 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
$3
- ❌ 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)
Works well with
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 |
Key Features
- 🔐 Autenticação JWT - Automatic login with interceptors
- 🛡️ Route Protection - Role-based RequireAuth component
- 📊 Request Hook - useRequest with 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
Complete Documentation
For detailed examples, usage guides, and API references, please visit:
Complete Documentation
Developer usage
Contributing
We welcome contributions! Please see our Contributing Guide for details.
$3
`bash
Clone repository
git clone https://github.com/forgepack/request.git
cd request
Install dependencies
npm install
Run tests
npm test
Build
npm run build
`
Code of Conduct
Please read our Code of Conduct before contributing.
Author and Developers
- GitHub: Gadelha TI
- Website: forgepack.dev
License
This project is licensed under the MIT License - see the MIT LICENSE file for details.
`text
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.
``