Search code examples
next.jsnext.js13next-api

How can I use the nextjs API route in my deployment environment?


my nextjs version - 13.2.1

First of all, the code below works normally in a local environment.


// src/pages/api/md/index.ts
// get markdowns data

import type { NextApiRequest, NextApiResponse } from "next";
import { join } from "path";
import fs from "fs/promises";
import matter from "gray-matter";
import { MarkDownProps } from "@/types/pages";

type Error = {
  error: string;
};

type Data = MarkDownProps[] | Error;

type Send<Data> = (data: MarkDownProps[]) => void;

type newApiResponse = {
  send: Send<Data>;
  json: Send<Data>;
  status: (statusCode: number) => NextApiResponse<Data>;
};

export default async function handler(
  req: NextApiRequest,
  res: newApiResponse,
) {
  if (req.method === "GET") {
    try {
      const result = await getMdList();
      res.status(200).send(result);
    } catch (error) {
      res.status(500).send({ error: "failed to fetch data" });
    }
  }
}

export const getMdList = async () => {
  ...some code
  return posts;
};

async function getMdFiles(dirPath: string): Promise<string[]> {
  ...some code
  return mdFiles;
}



// Components that use the API
// get markdowns data

const listfetch = async () => {
    const response = await axios.get("/api/md");
    if (pathname.split("/")[1] === "blog") {
      setRecommandList(
        response.data.filter(
          (item: MarkDownProps) => item.category === "github",
        ),
      );
    } else {
      setRecommandList(
        response.data.filter(
          (item: MarkDownProps) => item.category === pathname.split("/")[1],
        ),
      );
    }
  };

  useEffect(() => {
    listfetch();
  }, []);

this code is receive data well in local. but not found in deployment

error :GET https://{my URL}/api/md 404

think about what this needed more, i add pageExtensions in next.config but didnt work too

my config is this


/** @type {import('next').NextConfig} */
const nextConfig = {
  reactStrictMode: false,
  images: {
    unoptimized: true,
  },
  compiler: {
    styledComponents: true,
  },
  pageExtensions: ["js", "jsx", "ts", "tsx", "md", "mdx"],
};

module.exports = nextConfig;


how can i resolve this problem??


Solution

  • cannot use page/api dir in static deployment envirment