redis 如何使用Nextjs 14服务器操作使用Upstash限制费率(使用IP地址)

fdx2calv  于 6个月前  发布在  Redis
关注(0)|答案(1)|浏览(78)

问题很简单,一切都在文章的标题中得到了解释。
如何实现速率限制使用用户的IP地址与服务器动作?
我故意写了这段代码,所以它会有错误,所以我可以演示。

"use server"

// NEXTJS IMPORTS
import { auth } from "@/auth";

// CONFIG
import { API_ERROR_MESSAGES } from "@/app/config";

// ACTIONS
import { getUserIdByUsername } from "@/app/actions/add_post/getUserIdByUsername";

// REDIS
import { getCache, setCache } from "@/app/actions/redis/redisFunctions";
import { Redis } from '@upstash/redis';
import { Ratelimit } from "@upstash/ratelimit";

// DATABASE
import { database } from "@/app/lib/database";

const ratelimit = new Ratelimit({
    redis: Redis.fromEnv(),
    limiter: Ratelimit.slidingWindow(1, "10 s")
})

export async function createMentions(description: string, postId: number, commentId?: number) {
    const ip = request.headers.get("x-forwarded-for") ?? ""; // HERE LIES THE ISSUE, WE CANNOT SET HEADERS LIKE THIS SINCE IT IS SERVER ACTION, AND WE DONT HAVE ACCESS TO REQUEST (As of my knowledge)
    const { success, reset } = await ratelimit.limit(ip);

    if(!success) {
        const now = Date.now();
        const retryAfter = Math.floor((reset - now) / 1000);

        /*

        THIS IS HOW IT WOULD LOOK LIKE IF WE WERE USING API ENDPOINT WITH NextResponse

        return new NextResponse("Too many requests", {
            status: 429,
            headers: {
                ["retry-after"]: `${retryAfter}`,
            },
        }); 

        */

        return { success: false, error: { code: "TOO_MANY_REQUESTS" }} // HOW I WANT IT TO BE
    }

return { success: true, error: { code: "SOME_SUCCESS_MESSAGE" }}

字符串
我试着研究这个问题,但没有找到任何解决方案(PS:我确实做了,但这并不好)。

hkmswyz6

hkmswyz61#

您可以从next/headers使用headers()函数。
https://github.com/vercel/next.js/issues/47793

"use server";

import { headers } from "next/headers";

export async function getIp() {
  const ip = headers().get("x-forwarded-for");

  return ip;
}

字符串

相关问题