Skip to content

How can I use files in Serverless Functions on Vercel?

You can import files to be used inside a Vercel Serverless Functions as follows:

// api/hello.js import { readFileSync } from 'fs'; import path from 'path'; export default function handler(req, res) { const file = path.join(process.cwd(), 'files', 'test.json'); const stringified = readFileSync(file, 'utf8'); res.setHeader('Content-Type', 'application/json'); return res.end(stringified); }

An example Serverless Function that reads from the filesystem.

Next.js

You can also read files from inside server-side Next.js data fetching methods like getStaticProps or with API Routes, both of which use Serverless Functions when deployed to Vercel:

// pages/index.js

import { readFileSync } from 'fs';
import path from 'path';

export function getStaticProps() {
  const file = path.join(process.cwd(), 'posts', 'test.json');
  const data = readFileSync(file, 'utf8');

  return {
    props: {
      data,
    },
  };
}

export default function Home({ data }) {
  return <code>{data}</code>;
}

A Next.js application that reads from the filesystem.

Couldn't find the guide you need?