You can import files to be used inside a Vercel Serverless Functions as follows:
1// api/hello.js2
3import { readFileSync } from 'fs';4import path from 'path';5
6export default function handler(req, res) {7 const file = path.join(process.cwd(), 'files', 'test.json');8 const stringified = readFileSync(file, 'utf8');9
10 res.setHeader('Content-Type', 'application/json');11 return res.end(stringified);12}
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:
1// pages/index.js2
3import { readFileSync } from 'fs';4import path from 'path';5
6export function getStaticProps() {7 const file = path.join(process.cwd(), 'posts', 'test.json');8 const data = readFileSync(file, 'utf8');9
10 return {11 props: {12 data,13 },14 };15}16
17export default function Home({ data }) {18 return <code>{data}</code>;19}
Using temporary storage
Sometimes, you may need to save a file temporarily before sending it for permanent storage to a third-party storage service like Amazon S3. For example, if you are generating a PDF from content that is provided on the client-side, you will first need to save the PDF data temporarily before you can upload it to your the third-party storage service. In this case, you can use the /tmp
folder available with serverless functions.
The example code below is for an api endpoint that you can call from the front-end. You pass the title and filename of the PDF file to be created as query parameters. It uses pdfkit to create the pdf file and write it to the tmp
folder so that the PDF content is read from that location and passed to the parameters of the AWS S3 SDK.
1// api/savepdf.js2
3const PDFDocument = require('pdfkit');4const fs = require('fs');5import aws from 'aws-sdk';6
7export default async function handler(req, res) {8 //Send the data for the pdf in the request as query params such as the title and filename9 const {10 query: { title, filename },11 } = req;12 const doc = new PDFDocument();13 //use the tmp serverless function folder to create the write stream for the pdf14 let writeStream = fs.createWriteStream(`/tmp/${filename}.pdf`);15 doc.pipe(writeStream);16 doc.text(title);17 doc.end();18
19 writeStream.on('finish', function () {20 //once the doc stream is completed, read the file from the tmp folder21 const fileContent = fs.readFileSync(`/tmp/${filename}.pdf`);22 //create the params for the aws s3 bucket23 var params = {24 Key: `${filename}.pdf`,25 Body: fileContent,26 Bucket: 'your-s3-bucket-name',27 ContentType: 'application/pdf',28 };29
30 //Your AWS key and secret pulled from environment variables31 const s3 = new aws.S3({32 accessKeyId: process.env.YOUR_AWS_KEY,33 secretAccessKey: process.env.YOUR_AWS_SECRET,34 });35
36 s3.putObject(params, function (err, response) {37 res.status(200).json({ response: `File ${filename} saved to S3` });38 });39 });40}