Module 6: API Routes

Lesson 1: Creating API Routes

Next.js allows you to create serverless API routes for handling backend logic directly in your application. These routes are created inside the pages/api/ directory.

  • Basic API Route:

export default function handler(req, res) { res.status(200).json({ message: ‘API Route Working!’ });
}

  • File Structure:
    • pages/api/example.js -> Accessible at /api/example .
  • Use Cases:
    • Fetch data from external APIs and process it.
    • Handle form submissions.
    • Create CRUD operations for your app.

Lesson 2: Handling Requests and Responses

API routes handle HTTP methods like GET, POST, PUT, DELETE, etc. Using the req (request) and res (response) objects, you can define the logic based on the request type.

  • Example: Handling Different HTTP Methods:

export default function handler(req, res) { if (req.method === ‘GET’) {
res.status(200).json({ message: ‘This is a GET request’ });
} else if (req.method === ‘POST’) { const data = req.body;
res.status(201).json({ message: ‘POST request received’, data });
} else {
res.status(405).json({ message: ‘Method Not Allowed’ });
}
}

    • Parsing JSON Data:
      • By default, Next.js parses incoming JSON payloads.
      • Ensure your request headers include Content-Type: application/json for POST requests.

Lesson 3: Middleware in API Routes

Middleware functions add additional processing logic to API routes. They can be used for tasks such as authentication, logging, or request validation.

  • Example: Middleware for Authentication:

export default function handler(req, res) { const { authorization } = req.headers;

if (!authorization || authorization !== ‘Bearer mysecrettoken’) { return res.status(401).json({ message: ‘Unauthorized’ });
}

res.status(200).json({ message: ‘Authorized request’ });
}

    • Using Third-Party Middleware:
      • Libraries like cors can be integrated easily:

import Cors from ‘cors’;
const cors = Cors({ methods: [‘GET’, ‘POST’] });
function runMiddleware(req, res, fn) {
return new Promise((resolve, reject) => { fn(req, res, (result) => {
if (result instanceof Error) { return reject(result);
}
return resolve(result);
});
});
}

export default async function handler(req, res) { await runMiddleware(req, res, cors); res.status(200).json({ message: ‘CORS enabled!’ });
}

Additional Resources

API Routes Docs


Comments

Leave a Reply

Your email address will not be published. Required fields are marked *