Skip to content

Instantly share code, notes, and snippets.

@grmkris
Last active October 25, 2022 20:30
Show Gist options
  • Select an option

  • Save grmkris/042847edd9727adfcff03e610b01a93c to your computer and use it in GitHub Desktop.

Select an option

Save grmkris/042847edd9727adfcff03e610b01a93c to your computer and use it in GitHub Desktop.
NextJS IPFS Infura proxy
// Put this file in your nextjs project at /api/ipfs/[ipfs-infura-proxy].ts
// run:
// yarn add next-http-proxy-middleware
import httpProxyMiddleware from "next-http-proxy-middleware";
import { NextApiRequest, NextApiResponse } from "next";
import { env } from "../../../env/server.mjs";
// For preventing header corruption, specifically Content-Length header
export const config = {
api: {
bodyParser: false,
},
};
export default (req: NextApiRequest, res: NextApiResponse) => {
console.log("Proxying request to IPFS Infura");
const projectId = env.INFURA_PROJECT_ID;
const apiSecretKey = env.INFURA_API_SECRET_KEY;
const authorization =
"Basic " + Buffer.from(`${projectId}:${apiSecretKey}`).toString("base64");
return httpProxyMiddleware(req, res, {
target: "https://ipfs.infura.io:5001",
pathRewrite: [
{
patternStr: "/api/ipfs/",
replaceStr: "/api/v0/",
},
],
headers: { authorization },
});
};
import { useMutation } from "@tanstack/react-query";
import { create } from "ipfs-http-client";
import { AddResult } from "ipfs-http-client/add-all";
export const uploadToIpfs = async (data: File | string): Promise<AddResult> => {
const client = create({
host: "localhost:3000",
apiPath: "api/ipfs",
protocol: "http",
});
const result = await client.add(data);
console.log("result", result);
return result;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment