Setup a Nextjs API with Cors

How to Create a Nextjs API route


Setup a API in Nextjs is so easy, navigate pages folder under your project, and locate the API folder.

In Next each folder under Pages is treated as sub route. There will be default hello API for better under stand what going on.

In my example I also used Prisma ORM for easy data fetching and also prefer to use Typescript.

Under the API folder create a file called users.ts/users.js and add the following code.

// Next.js API route support: https://nextjs.org/docs/api-routes/introduction
 
 
import { NextApiRequest, NextApiResponse } from 'next';

import NextCors from 'nextjs-cors';
import prisma from '../../lib/prisma-client';
 export default async function handler(
  req: NextApiRequest,
  res: NextApiResponse
) {

  await NextCors(req, res, {
    // Options
    methods: ['GET', 'HEAD', 'PUT', 'PATCH', 'POST', 'DELETE'],
    origin: '*',
    optionsSuccessStatus: 200, // some legacy browsers (IE11, various SmartTVs) choke on 204
 });

}

Cors

Cors is required for to tackle same origin error, so there is special module is for Next users, **NextCors**

Install the dependecy using console

yarn add nextjs-cors

The handler will do the API task.

Author: Manoj

Developer and a self-learner, love to work with Reactjs, Angular, Node, Python and C#.Net

Leave a comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.