0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Next.js(Pages Router)でAPIルートからIPアドレスを取得する方法

Posted at

はじめに

Next.js(Pages Router)でAPIルートからIPアドレスを取得する方法を備忘録として残します。

環境

"next": "13.2.4",

コード

リクエストのヘッダーにあるx-forwarded-forで取得できます。

/api/ip/getIp.ts
import type { NextApiRequest, NextApiResponse } from 'next';

export default async function handler(
  req: NextApiRequest,
  res: NextApiResponse,
) {
  const data = {
    ip: req.headers['x-forwarded-for'],
  };

  return res.status(200).json(data);
}

HTTPリクエストにaxiosを使用してますが、何でも良いです。

import axios from 'axios';

type Ip = {
  ip: string;
};

export const fetchIp = async () => {
  const { data } = await axios.get<Ip>('/api/ip/getIp');

  return data;
};

注意

ローカル環境では、プロキシサーバーなどのネットワーク機器が存在しないため、x-forwarded-forが取得できません。サーバーにデプロイすれば取得できるようになります。

最後に

GoQSystemでは一緒に働いてくれる仲間を募集中です!

ご興味がある方は以下リンクよりご確認ください。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?