Last active
October 25, 2022 20:30
-
-
Save grmkris/042847edd9727adfcff03e610b01a93c to your computer and use it in GitHub Desktop.
NextJS IPFS Infura proxy
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| // 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 }, | |
| }); | |
| }; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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