#nextjs 14
1 messages · Page 1 of 1 (latest)
Securing your API routes in Next.js can be achieved by implementing a secret token string that is only known by your Next.js app and your headless CMS. This secret prevents people who don’t have access to your CMS from accessing your API routes. Here are the steps you can follow:
-
Create a secret token string using a token generator of your choice.
-
If your headless CMS supports setting custom URLs, specify the following as the URL. This assumes that your API route is located at
pages/api/your-route.js.
<https://<your-site>/api/your-route?secret=<token>&slug=<path>>
<your-site>should be your deployment domain.<token>should be replaced with the secret token you generated.<path>should be the path for the page that you want to view.
- In your API route, check that the secret matches and that the
slugparameter exists. If not, the request should fail.
Here's an example of how you might implement this in your API route:
export default async (req, res) => {
// Check the secret and next parameters
// This secret should only be known to this API route and the CMS
if (req.query.secret !== 'MY_SECRET_TOKEN' || !req.query.slug) {
// Handle the error...
}
// Continue with your logic...
}
Remember to replace 'MY_SECRET_TOKEN' with your actual secret token.
For more details, you can refer to the following sources:
- Next.js Docs - Draft Mode (https://nextjs.org/docs/pages/building-your-application/configuring/draft-mode)
- Next.js Docs - Preview Mode (https://nextjs.org/docs/pages/building-your-application/configuring/preview-mode)
- Next.js Docs - On-Demand Revalidation (https://nextjs.org/docs/pages/building-your-application/data-fetching/incremental-static-regeneration)
Note: you can ask me a follow up question by @ mentioning me again :speech_balloon:
@vestal kayak kapa.ai is still learning and improving, please let us know how it did by reacting below
Let me check the knowledge base for you. One moment! :books:
In Next.js, environment variables that are not prefixed with NEXT_PUBLIC_ are only available in the Node.js environment, meaning they aren't accessible to the browser. If you want to use the value of an environment variable in the browser, you have to prefix the variable with NEXT_PUBLIC_. However, this will expose the variable to the client, which is not what you want for sensitive data like an API key.
To securely use your NEXT_API_KEY in a client function like getUsers, you should create a server-side API route in your Next.js application that interacts with the external API. This way, your API key is kept secure on the server and is not exposed to the client.
Here's a basic example of how you might set this up:
-
Create a new file in the
pages/apidirectory, for examplepages/api/users.js. -
In this file, you can access your
NEXT_API_KEYand make requests to your external API:
// pages/api/users.js
export default async (req, res) => {
const response = await fetch('<https://external-api.com/users',> {
headers: {
authorization: process.env.NEXT_API_KEY,
},
});
const data = await response.json();
res.status(200).json(data);
};
- Now, in your client function
getUsers, you can fetch data from this server-side API route instead of the external API:
// client-side function
async function getUsers() {
const res = await fetch('/api/users');
const data = await res.json();
// ...
}
This way, your NEXT_API_KEY is never exposed to the client, and you can securely fetch data from your external API.
For more information, refer to the following sources:
- Next.js Docs - Environment Variables (https://nextjs.org/docs/app/building-your-application/configuring/environment-variables)
- Next.js Docs - API Routes (https://nextjs.org/docs/app/building-your-application/configuring/api-routes)
Note: you can ask me a follow up question by @ mentioning me again :speech_balloon:
@vestal kayak kapa.ai is still learning and improving, please let us know how it did by reacting below
Let me check the knowledge base for you. One moment! :books:
To use a server-side function like getUsers in a client component, you can create an API route in Next.js and then call this API route from your client component. Here's a basic example of how you might set this up:
-
Create a new file in the
pages/apidirectory, for examplepages/api/users.js. -
In this file, you can use your
getUsersfunction to fetch the data:
// pages/api/users.js
import { getUsers } from '../../server-actions';
export default async (req, res) => {
const users = await getUsers();
res.status(200).json(users);
};
- Now, in your client component, you can fetch data from this server-side API route:
// client-side component
import { useEffect, useState } from 'react';
function UserList() {
const [users, setUsers] = useState([]);
useEffect(() => {
const fetchData = async () => {
const res = await fetch('/api/users');
const data = await res.json();
setUsers(data);
};
fetchData();
}, []);
return (
<ul>
{users.map(user => (
<li key={user.id}>{user.name}</li>
))}
</ul>
);
}
export default UserList;
In this example, UserList is a React component that fetches user data from the server-side API route when it mounts, and then renders a list of users.
For more information, refer to the following sources:
- Next.js Docs - API Routes (https://nextjs.org/docs/app/building-your-application/configuring/api-routes)
- Next.js Docs - Data Fetching (https://nextjs.org/docs/pages/building-your-application/data-fetching)