1 minute read
Building and Deploying Serverless Applications with NextJS and Vercel
When you deploy your NextJS application with Vercel, any serverless functions in the pages/api directory are automatically deployed as well. These functions are hosted on Vercel’s edge network, ensuring low-latency access for users around the world.
● Accessing Your Serverless Function
Advertisement
Once deployed, your serverless function can be accessed using its URL, which is based on the file path within the pages/api directory. For example, a serverless function in a file named pages/api/hello.js would be accessible at https://your-domain.com/api/hello. You can call this URL from your NextJS application using standard web APIs, such as fetch or axios.
● Using Middleware
Middleware functions allow you to perform common tasks, such as authentication or validation, before your serverless function’s main logic is executed. To use middleware with your serverless function, create a separate function that processes the req and res objects, and then call it within your main handler function. import middleware from '../middleware/middlewareFunction'; export default async function handler(req, res) {
// Call middleware function await middleware(req, res);