Home > Mobile >  trying to hide api but backend gives me error
trying to hide api but backend gives me error

Time:01-24

image of the error I am trying to build nft search app that when you give adress it finds the nfts that a wallet has. but i am using alchemy and don't want to expose api key. Don't know backend, using next.js.

my backend code:

const express = require("express");
const axios = require("axios");
const dotenv = require("dotenv");
dotenv.config();

const app = express();
const port = process.env.PORT || 3000;

app.use(express.json());
app.use(express.urlencoded({ extended: true }));

app.get("/api", (req, res) => {
  const apiKey = process.env.API_KEY;
  const owner = req.query.owner;
  const baseURL = `https://eth-mainnet.g.alchemy.com/nft/v2/${apiKey}/getNFTs/`;
  const fetchURL = `${baseURL}?owner=${owner}`;
  axios
    .get(fetchURL)
    .then((response) => {
      res.json(response.data);
    })
    .catch((error) => {
      res.json({ error: error.message });
    });
});

app.listen(port, () => {
  console.log(`Server is running on port ${port}`);
});

my frontend

 const fetchNFTs = async () => {
    const response = await fetch(`/api?${wallet}`);
    const nfts = await response.json();
    setNFTs(nfts);
  };

I tried chat gpt, serverless function but I failed to achieve results

CodePudding user response:

Is this a separate Express server? By default Next.js runs on port 3000, and that's why you're making a GET to localhost:3000. But if your Next.js server is started, your custom Express server would pick a different port because the 3000 is going to be taken. So your const response = await fetch('/api?${wallet}'); will result in a 404 because there's no such route in your Next.js app.

You could move your function into a Next.js API handler if you want your backend and frontend to live under the same port. Also you wouldn't need to manually create the express server and take care of the dotenv since Next.js is going to take care of that for you.

  • Related