API Routes with CORS

🔗

The folder for this example is here

What this does

This allows you to create an API endpoint with cors headers

Installing the needed packages

For this you will just need the cors package

npm install cors

Creating the API file

API's are stored in the pages/api folder, so for this example you can put cors.js in there

Inside that file, you can initially add the most basic API route, this will return a 200 response with the json shown

export default function handler(req, res) {
res.status(200).json({ name: 'John Doe' })
}

Helper method

Now we want to create a helper method for using middleware