next-token-cookie-manager
Version:
A library to manage storing login tokens in HTTP-only cookies in Next.js applications.
253 lines (169 loc) • 6.2 kB
Markdown
# Next Token Cookie Manager





**Next Token Cookie Manager** is a robust library designed to manage tokens in HTTP-only cookies seamlessly within Next.js applications. It simplifies authentication workflows by providing intuitive utility functions and pre-configured API routes, ensuring secure and efficient token management across various Next.js versions.
## Table of Contents
- [Features](#features)
- [Installation](#installation)
- [Getting Started](#getting-started)
- [Initialization](#initialization)
- [Using Utility Functions](#using-utility-functions)
- [API Routes](#api-routes)
- [/api/login](#apilogin)
- [/api/access](#apiaccess)
- [Examples](#examples)
- [API Reference](#api-reference)
- [Contributing](#contributing)
- [License](#license)
- [Contact](#contact)
## Features
- **Secure Token Storage:** Stores access tokens securely in HTTP-only cookies, mitigating XSS vulnerabilities.
- **Easy Integration:** Minimal setup required for quick integration into any Next.js project.
- **Utility Functions:** Provides \`setTokenCookie\` and \`getTokenCookie\` for easy token management.
- **Pre-configured API Routes:** Includes \`/api/login\` and \`/api/access\` routes to streamline authentication workflows.
- **TypeScript Support:** Fully typed for enhanced developer experience and safety.
- **CLI Tool:** Simplifies project setup by auto-generating the necessary API routes.
- **Compatibility:** Works with Next.js versions \`13.0.1\` and above.
## Installation
Install the package via npm or yarn:
```bash
npm install next-token-cookie-manager
# or
yarn add next-token-cookie-manager
```
## Getting Started
### Initialization
Initialize the package to set up the required API routes in your Next.js project. This step will create the \`login.ts\` and \`access.ts\` files in the appropriate API directory.
```bash
npx next-token-cookie-manager init
```
> **Note:** Ensure that your project uses Next.js version \`13.0.1\` or higher for optimal compatibility.
### Using Utility Functions
Next Token Cookie Manager provides utility functions to make token management easy.
#### `setTokenCookie`
Sets an access token in an HTTP-only cookie.
**Importing:**
```typescript
import { setTokenCookie } from 'next-token-cookie-manager';
```
**Usage:**
```typescript
const handleLogin = async () => {
const expiresIn = 3600; // 1 hour in seconds
const accessToken = 'your-access-token';
await setTokenCookie(expiresIn, accessToken);
};
```
#### `getTokenCookie`
Retrieves the access token from the HTTP-only cookie.
**Importing:**
```typescript
import { getTokenCookie } from 'next-token-cookie-manager';
```
**Usage:**
```typescript
const Profile = () => {
const [token, setToken] = useState<string | null>(null);
useEffect(() => {
const fetchToken = async () => {
const retrievedToken = await getTokenCookie();
setToken(retrievedToken);
};
fetchToken();
}, []);
return (
<div>
<h1>Profile Page</h1>
<p>Your token: {token}</p>
</div>
);
};
export default Profile;
```
## API Routes
Next Token Cookie Manager provides two primary API routes to handle authentication workflows:
### `api/login`
Handles user login and sets the access token in a cookie.
**Usage:**
Send a `POST` request to `/api/login` with the necessary credentials. Upon successful authentication, the access token will be stored in an HTTP-only cookie.
### `/api/access`
Retrieves the access token from the HTTP-only cookie.
**Usage:**
Send a `GET` request to `/api/access` to retrieve the stored access token.
## Examples
### Setting an Access Token
```typescript
// pages/index.tsx
import { setTokenCookie } from 'next-token-cookie-manager';
const handleLogin = async () => {
const expiresIn = 3600; // 1 hour in seconds
const accessToken = 'your-access-token';
await setTokenCookie(expiresIn, accessToken);
};
const LoginPage = () => (
<div>
<button onClick={handleLogin}>Login</button>
</div>
);
export default LoginPage;
```
### Retrieving an Access Token
```typescript
// pages/profile.tsx
import { useEffect, useState } from 'react';
import { getTokenCookie } from 'next-token-cookie-manager';
const Profile = () => {
const [token, setToken] = useState<string | null>(null);
useEffect(() => {
const fetchToken = async () => {
const retrievedToken = await getTokenCookie();
setToken(retrievedToken);
};
fetchToken();
}, []);
return (
<div>
<h1>Profile Page</h1>
<p>Your token: {token}</p>
</div>
);
};
export default Profile;
```
## API Reference
### `setTokenCookie(expiresIn: number, accessToken: string): Promise<void>`
Sets an access token in an HTTP-only cookie.
**Parameters:**
- `expiresIn` (number): The duration in seconds until the cookie expires.
- `accessToken` (string): The access token to store.
**Returns:** `Promise<void>`
### `getTokenCookie(): Promise<string | null>`
Retrieves the access token from the HTTP-only cookie.
**Parameters:** None
**Returns:** `Promise<string | null>`
## Contributing
Contributions are welcome! Although the repository is private, you can still contribute by following these steps:
1. **Fork the Repository**
2. **Create a New Branch**
```bash
git checkout -b feature/YourFeature
```
3. **Commit Your Changes**
```bash
git commit -m "Add YourFeature"
```
4. **Push to the Branch**
```bash
git push origin feature/YourFeature
```
5. **Open a Pull Request**
Please reach out to the repository maintainer to grant access to review and merge your pull requests.
## License
This project is licensed under the MIT License.
## Contact
Edonis Alijaj
- **Email:** alijajedonis@gmail.com
- **GitHub:** [edonis-create](https://github.com/edonis-create)