How to use Server-side configuration In Next.js
Normally, CORS is configured at the server level. This involves setting headers to control which origins are allowed to access resources on the server. While this approach is common in traditional server setups, it requires separate server maintenance and configurations.
In the server-side configuration approach, CORS middleware is applied globally to the server instance, ensuring that all requests are subject to CORS policy. The Cors middleware allows requests only from the specified origin.
Install the Cors package with the following command in your server folder.
npm i cors
// express.js ----> index.js
const express = require("express");
const cors = require("cors");
const app = express();
// Enable CORS for requests from localhost:3000
app.use(
cors({
origin: "http://localhost:3000",
optionsSuccessStatus: 200,
// Some legacy browsers choke on 204
})
);
app.get("/", (req, res) => {
res.send("Hello from Express server!");
});
const PORT = 3001;
app.listen(PORT, () => {
console.log(`Server is running on port ${PORT}`);
});
lets make a request to our server from the index.js of the NextJs application and check the cors is working fine or not.
//next.js ---> index.js
import Head from "next/head";
import axios from "axios";
import { useEffect, useState } from "react";
function Home() {
const [msg, setMsg] = useState("");
useEffect(() => {
const fetchData = async () => {
try {
const response = await axios.get("http://localhost:3001/sendamsessage");
setMsg(response.data);
} catch (error) {
console.log(error);
}
};
fetchData();
}, []);
return (
<>
<Head>
<title>Create Next App</title>
</Head>
<main style={{ height: "100vh" }}>
<h2>{msg}</h2>
</main>
</>
);
}
export default Home;
To cross-verify, let’s change the allowed origin in the CORS configuration in index.js on the server to “http://localhost:3004”. After making this change, the expected behavior is that the CORS policy will only allow requests from “http://localhost:3004” and reject requests from “http://localhost:3000”.
How to use CORS in Next.js to Handle Cross-origin Requests ?
NextJS simplifies server-side logic with its API routes, reducing the need for separate server maintenance. CORS, usually configured on the server, can be handled within NextJS API routes directly. These routes, integrated into the application codebase, allow control over request origins. By implementing CORS in API routes, NextJS ensures secure and controlled access to server resources. This approach aligns with NextJS’s server-side rendering capabilities. Developers benefit from reduced complexity and streamlined maintenance.
NextJS emerges as a favorable framework for building applications with server-side rendering needs. Its integration of CORS management within API routes enhances security and flexibility. This model offers a unified solution for both client and server-side needs, promoting efficient development practices.
We Will discuss the different approaches to handling cross-origin requests using NextJS:
Table of Content
- Using Server-side configuration
- Enabling CORS for all API routes