Conquer CORS Errors in Your Next.js App: A Guide to Smooth Sailing
This blog post tackles a common challenge in Next.js applications: Cross-Origin Resource Sharing (CORS) errors and fetching data from an API. We'll provide a step-by-step approach with code snippets to ensure smooth communication between your frontend and backend.
Here's the Code Breakdown:
1. Next.js API Route (users.js):
import { NextResponse } from "next/server"; export function GET() { try { return NextResponse.json([ { name: "Testing 1", branch: "CS" }, { name: "Testing 2", branch: "CS" }, ]); } catch (err) { console.log(err); } }
This code defines a basic API route named /api/users
that responds to GET requests. It returns a pre-defined list of users in JSON format and includes error handling for logging any issues.
2. CORS Middleware (middleware.js):
import { NextResponse } from 'next/server' const allowedOrigins = ['http://localhost:3000']; // Replace with your allowed origins const corsOptions = { 'Access-Control-Allow-Methods': 'GET, POST, PUT, DELETE, OPTIONS', 'Access-Control-Allow-Headers': 'Content-Type, Authorization', } export function middleware(request) { // Check the origin from the request const origin = request.headers.get('origin') ?? '' const isAllowedOrigin = allowedOrigins.includes(origin) // Handle preflighted requests const isPreflight = request.method === 'OPTIONS' if (isPreflight) { const preflightHeaders = { ...(isAllowedOrigin && { 'Access-Control-Allow-Origin': origin }), ...corsOptions, } return NextResponse.json({}, { headers: preflightHeaders }) } // Handle simple requests const response = NextResponse.next() if (isAllowedOrigin) { response.headers.set('Access-Control-Allow-Origin', origin) } Object.entries(corsOptions).forEach(([key, value]) => { response.headers.set(key, value) }) return response } export const config = { matcher: '/api/:path*', }
This middleware plays a crucial role in enabling CORS. It defines allowed origins (allowedOrigins
) and allowed methods/headers (corsOptions
). The code checks the request origin and method:
- For preflight requests (OPTIONS method), it verifies if the origin is allowed and sets appropriate CORS headers.
- For simple requests, it adds necessary CORS headers to the response based on the origin and
corsOptions
.
Important Note: Remember to replace 'http://localhost:3000'
with your actual allowed origins for production environments. Allowing all origins with '*'
is for development purposes only.
3. React Component (App.js):
import axios from 'axios' import React from 'react' import { useEffect } from 'react' const App = () => { const findUser = async () => { try { const res = await axios.get('http://localhost:3000/api/users') console.log(res.data); } catch (error) { console.log(error) } } useEffect(()=>{ findUser() },[]) return ( <div>App</div> ) } export default App
This React component demonstrates fetching users from the API route using axios
. The findUser
function utilizes axios.get
to retrieve user data from the /api/users
endpoint. The response data is then logged to the console. Error handling is included (try...catch
) to manage any potential errors during the fetch process.
By implementing these steps, you'll have a robust system for fetching data from your Next.js API routes while ensuring secure communication across origins.