Reputation: 5061
I am worried that my Keys for various functions are exposed to the client. I have this function
onRunOCR = async (event) => {
const client = new SomeAPI({
credentials: {
accessKeyId: 'ffg23f23f23f32f23',
secretAccessKey: 'GZMIKGDoISDGpsgjMIPSGMDIPG',
},
})
}
This is basically an on click function in my class component. This is fully exposed to anyone right?
How can I secure it. Would NEXT_PUBLIC_ACCESS_KEY
work or is that the same just stores it as a variable?
Thanks
Upvotes: 1
Views: 5964
Reputation: 6598
Yes, keys are exposed in your example.
Anyone can access private keys that are exposed to the browser. The most common way to prevent key leakage is only to use them server-side.
You can create an API route or a custom endpoint like an AWS Lambda function that you call in your onClick
handler.
Using env variables in your server-side function is okay as they are never rendered to the browser.
.env file
API_KEY_ID=123456
API_ACCESS_KEY=ABCDEF
API route
export default function handler(_, res) {
const data = new SomeAPI({
credentials: {
accessKeyId: process.env.API_KEY_ID,
secretAccessKey: process.env.API_ACCESS_KEY,
},
})
res.status(200).json(data)
}
Other default Next.js server-side features/functions it's okay to place keys are getServerSideProps, getStaticProps, getStaticPaths, and middleware.
Upvotes: 4