Support Forums

Manually deploy NextJS API functions

My nextjs app was statically generated, and previously I was able to run next build && next export and deploy using netlify deploy

Now I have added some API routes and when automatic builds are enabled, the essential next plugin is able to create functions for me and the API is correctly mapped to /api/ routes. Is it possible to do this step manually with the netlify CLI?

I tried doing netlify deploy --functions="pages/api" and the functions are deployed, but they are mapped to netlify routes ("/.netlify/functions") instead of next routes ("/api/") like they would be with the plugin run during automatic builds.

Also, I haven’t checked this but I assume the function parameters would be different as well (netlify functions being event, context and nextJS functions having express styled res, res)

Hey there, @rosghub :wave:

Welcome to the Netlify Forums! Glad you found us. Before we dive in, could you share your Netlify site, your function name, and your repo (if public?)

This will help us discuss this in further detail. Thanks!

Hi @rosghub

If I have understood correctly, you are wanting to use Netlify functions but instead of using /.netlify/functions/<function-name> you want to use /api/<function-name>.

My method when deploying from the CLI it to set up a netlify.toml

  command = "<my-command>" # e.g. next build && next export
  functions = "path/to/functions" # default is `netlify/functions`
  publish = "<build-output-directory>" # e.g. `out`

But you will also want to set up a redirect too if you wish to use /api/<function-name> in your netlify.toml (see docs above)

  from = "/api/*"
  to = "/.netlify/function/:splat"

so you can call /api/<my-function> not /.netlify/functions/<my-function>

Perfect, that should solve the issue of routing

Now my only issue is that netlify function parameters (which uses AWS styled (event, context) params) are different than nextJS API route params (which use express styled (req, res) params).

And netlify functions depend on a return value where as nextJS API routes depend on a call to res.status()

Not sure how the nextJS plugin does it all.

I haven’t gone to great depths with Next.js, but I am thinking (possibly I am wrong) when they say

Any file inside the folder pages/api is mapped to /api/* and will be treated as an API endpoint instead of a page .

I am thinking this mapping is done internally (within the router).

Looking at the example on the docs you linked to, they use swr to handle calls to /api routes. This is Vercel documentation, so if/how it works on Netlify I cannot say.