Getting Started
Welcome to Nitro Fetch — a modern, lightweight HTTP client for JavaScript and TypeScript. This guide will walk you through the installation, basic setup, and usage examples so you can start making HTTP requests quickly and efficiently.
📦 Installation
Install Nitro Fetch using your preferred package manager:
- npm
- yarn
- pnpm
- Browser
npm install nitro-fetch
yarn add nitro-fetch
pnpm add nitro-fetch
Using jsDelivr CDN:
<script src="https://cdn.jsdelivr.net/npm/nitro-fetch@1.0.1/dist/umd/nitro-fetch.min.js"></script>
Using unpkg CDN:
<script src="https://unpkg.com/nitro-fetch@1.0.1/dist/umd/nitro-fetch.min.js"></script>
Importing Nitro Fetch
Nitro Fetch supports both ES Modules (ESM) and CommonJS (CJS) formats, allowing you to use it in modern front-end apps or Node.js environments.
ES Modules
import { create } from 'nitro-fetch';
CommonJS
const { create } = require('nitro-fetch');
Creating an Instance
The create()
function initializes a new Nitro Fetch instance with optional global configuration such as baseURL
, headers
, and timeout
.
const api = create({
baseURL: 'https://jsonplaceholder.typicode.com',
timeout: 5000, // Optional: request timeout in milliseconds
headers: {
Authorization: 'Bearer <your-token>',
},
});
This instance can now be reused for all API calls, keeping your configuration centralized and consistent.
Making a GET Request
Making a simple GET
request is straightforward:
api.get('/posts/1')
.then(response => {
console.log('Data:', response.data);
})
.catch(error => {
console.error('Error:', error);
});
response.data
contains the parsed JSON response.- The
.catch()
block handles any network or server errors gracefully.
Making a POST Request
You can also easily send data using POST
, PUT
, or PATCH
methods.
api.post('/posts', {
title: 'Hello World',
body: 'This is a test post.',
})
.then(response => {
console.log('Created Post:', response.data);
})
.catch(error => {
console.error('Error creating post:', error);
});
All request bodies are sent as application/json
by default, unless otherwise configured.
🧠 TypeScript Example
Nitro Fetch is fully typed out of the box. You can specify generic types to get type-safe responses.
import { create, Response } from 'nitro-fetch';
interface Post {
id: number;
title: string;
body: string;
}
const api = create({ baseURL: 'https://jsonplaceholder.typicode.com' });
async function fetchPost() {
try {
const response: Response<Post> = await api.get<Post>('/posts/1');
console.log(response.data.title); // Type-safe access
} catch (err) {
console.error('Failed to fetch post:', err);
}
}
Use your Nitro Fetch instance across your entire app by exporting it from a dedicated file like api.ts
Ready to build faster and smarter?
Head over to the API Reference to explore all available options.