What is the Vercel version of .netlify/functions?

Viewed 54

I am trying to deploy this repo: https://github.com/DataStax-Examples/astra-tik-tok with Vercel instead of Netlify.

I refactored vanilla React into Next.js, but in the Home.js file I don't understand how to migrate this over to Vercel's equivalent:

//fetch all the tik-tok posts to your feed
const fetchData = async () => {
    const results = await axios.get('/.netlify/functions/posts')
    console.log(results.data)
    setUsers(results.data)
}

Any ideas?

1 Answers

The equivalent in Next.js are API routes, which get deployed as serverless functions in Vercel. They must be created under the /pages/api folder.

You need to slightly refactor the functions to work with Next.js. For example, your add.js function would look like the following as an API route.

// /pages/api/add.js
export default function handler(req, res) {
    const users = await getCollection();
    try {
        const user = await users.create(id, event.body);
        res.status(200).json(user);
    } catch (e) {
        console.error(e);
        res.status(500).json({ error: JSON.stringify(e) })
    }
};

You would then call the API route from the client-side code by pointing to /api/add.

await axios.get('/api/add')
Related