next-export-api
v0.1.11
Published
Next.js API Routes adaptor for a Netlify static website
Downloads
26
Maintainers
Readme
Next Export API
Installation
yarn add next-export-api
or
npm install next-export-api
Ensure to install it as a production dependency, not a development one.
Add next-export-api
to the build script. You can use postbuild
if you are using build
on the package.json
:
{
"name": "example",
"scripts": {
"build": "next build && next export",
+ "postbuild": "next-export-api",
"dev": "next dev",
"start": "next start"
},
"dependencies": {
"next": "9.5.5",
"react": "16.14.0",
"react-dom": "16.14.0"
}
}
Configure netlify.toml
to define functions directory:
[build]
command = "yarn build"
publish = "out"
functions = "out/api"
Both
publish
andfunctions
above are configurable, and will be respected bynext-export-api
command.
Please check the example folder for a ready to deploy sample project.
Motivation
Over a year ago Next.js released version 9 with API Routes support. Netlify has also long supported their vision of serverless functions. The issue? They have very diverging APIs. Next.js even states, in a caveats section, it's API Routes do not work with next export
projects - the most straightforward way of deploying Next.js projects on Netlify. However, with a bit of adaptation from generated API Routes entrypoints files, it's possible to make them capable of running on Netlify functions environment.
Similar projects
This project is heavily inspired by...
The difference to these projects is next-export-api
focuses in allowing the use of API Routs on a Next.js Static HTML Exported project.
How does it work
Similarly to next-on-netlify
, this project takes advantage of Next.js own building system, and operates on it's generated code. As for API Routes, Next.js does generate a self-contained file for each /pages/api
entrypoint, meaning we can import those files or of the foreseen context of a Next.js server.
The process is like the following:
Next.js builds into the
.next
directory;Next.js exports static site into (configurable)
out
directory;next-export-api
reads page manifests from the.next
build, and...Creates one file for each API route under
out/api
These files are thin wrappers over Next.js original ones, only adapting for execution on AWS using well supported
serverless-http
.Creates
_redirects
rules for each of the API routes above, mapping/api/*
calls to/.netlify/functions/*
as expected by Netlify