How to invalidate array of sluges in Next.js?

Since 12.1.0 it is possible the On-demand Revalidation.

Sending array of programIds, how can I invalidate array of slugs? I tried this:

export default async function handler(req, res) {
    // Check for secret to confirm this is a valid request
    if (req.query.secret !== process.env.NEXT_PUBLIC_SECRET_TOKEN) {
        return res.status(401).json({ message: 'Invalid token' })

    try {
        const programIds: String[] = req.query.programId =>
            await res.unstable_revalidate(`/hu/buyTicket/${programId}`)
        return res.json({ revalidated: true })
    } catch (err) {
        // If there was an error, Next.js will continue
        // to show the last successfully generated page
        return res.status(500).send('Error revalidating')

I got this error:

‘await’ expressions are only allowed within async functions and at the top levels of modules.


Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

.map does not respect await even if you use async. In your situation, you will receive a response before revalidation is completed, which is incorrect behavior.

The correct method should include the usage of Promise.all so that res.json is called only after all the revalidations are completed, and try/catch block can catch error correctly.

  await Promise.all( (programId) =>
        await res.unstable_revalidate(`/hu/buyTicket/${programId}`)

All methods was sourced from or, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Notify of

Inline Feedbacks
View all comments
Would love your thoughts, please comment.x