1.1.6 • Published 10 months ago

next-app-api-route v1.1.6

Weekly downloads
-
License
MIT
Repository
github
Last release
10 months ago

Usage Guide

This package provides a simple way to define API routes with authentication and middleware support in a Next.js application. The code below demonstrates how to create middleware and handle any HTTP requests.

Installation

First, you need to install the package in your Next.js project:

npm install next-app-api-route

Example Usage

import ApiRoute, { NextChain } from "next-app-api-route";
import { NextRequest, NextResponse } from "next/server";

const router = new ApiRoute();

// Middleware function to check authentication
const middlewarefun: NextChain = async (req, params, next, cache) => {
  // Check if the request is authenticated (replace with actual authentication logic)
  const authenticated = false; // For demo purposes, authentication is false

  if (!authenticated) {
    // If not authenticated, return a 401 Unauthorized response
    return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
  }

  cache.setData("data", { id: 1 });

  // If authenticated, proceed to the next handler
  return next();
};

// Handler for GET requests
const getData: NextChain = async (req, params, next, cache) => {
  console.log(cache.getData("data")); // "{id:1}"
  return NextResponse.json({ message: "Success" });
};

// Handler for POST requests
const postData: NextChain = async (req, res) => {
  return NextResponse.json({ message: "Data created successfully" });
};

// Apply middleware to the GET route, followed by the handler function
export const GET = router.use(middlewarefun, getData);

// Apply the POST handler (no middleware applied here)
export const POST = router.use(postData);
1.1.6

10 months ago

1.1.5

10 months ago

1.1.4

10 months ago

1.1.3

10 months ago

1.1.2

10 months ago

1.1.1

10 months ago

1.1.0

10 months ago

1.0.9

10 months ago

1.0.8

10 months ago

1.0.7

10 months ago

1.0.5

10 months ago

1.0.4

10 months ago

1.0.3

10 months ago

1.0.2

10 months ago

1.0.1

10 months ago

1.0.0

10 months ago