Not awaiting async function inside of non-edge API route/server actions. #66306
Replies: 2 comments
-
|
The answer here is |
Beta Was this translation helpful? Give feedback.
-
|
I would split this into two cases: work that must complete before you can honestly return success, and side effects that are allowed to happen after the response. For the S3 example, the upload is not a background side effect. It is the main mutation. I would await it: await client.send(command)
return `Woohoo, you uploaded ${fileName}`If you do not await it, the action can return success while the upload is still pending or has already failed. On Vercel, even in the Node.js runtime, you should still treat the invocation as request-scoped. It is not a durable always-on worker where floating promises are a reliable contract. For logging/analytics/non-critical cleanup, use import { after } from 'next/server'
export async function POST(req: NextRequest) {
const user = await getUser()
if (!user.isAdmin()) {
return Response.json({ error: 'Unauthorized' }, { status: 401 })
}
const { key, value } = await req.json()
await prisma.settings.update({
where: { key },
data: { value },
})
after(() => {
log(`${user.name} updated ${key} to ${value}`)
})
return Response.json({ ok: true })
}
So the short version is:
|
Beta Was this translation helpful? Give feedback.
Uh oh!
There was an error while loading. Please reload this page.
Uh oh!
There was an error while loading. Please reload this page.
-
Summary
So, I've read a bit about how you have to await everything in an edge function because they run on Lambda which die shortly after the function returns. Does this also apply to server actions and API routes?
I guess this is really a question of infrastructure when deploying on Vercel. Locally, I can do this just fine.
When I deploy to Vercel, will the Next server run distributed or as an actual server/cluster? Can I specify that the various server actions and API routes not run on Edge.
Even if Next deploys to a server cluster, will it kill processes even if there are unresolved promises?
I've provided some code snippets which are more or less pseudo-code for use cases in the codebase I'm working on.
TL;DR: Do you have to await all async functions in server actions and API routes that do not run on the Edge?
Additional information
Beta Was this translation helpful? Give feedback.
All reactions