Next.js Discord

Discord Forum

Protecting SendGrid API endpoint

Unanswered
Sun bear posted this in #help-forum
Open in Discord
Sun bearOP
I'm using @sendgrid/mail package in a serverless function to send emails from my app... Does anyone have a good way to protect that endpoint from possible use by outside parties?
We're using NextAuth, but an email needs to be sent from the app before a user is "approved"/allowed to login, so protecting it based on role or userId isn't an option.

Any help/suggestions would be helpful!

9 Replies

@Sun bear do you have some api route that sends emails?
If so just add an argument to the request to either the header, body or url
Which contains some key you generate yourself and saved in end variables
Anyone can call your email api route, but it will check for the existence of the secret key before running logic
If you add that check
The nuance here is that you can’t call this function in any browser facing code
Since the key would be visit when being sent in a fetch request
Asian black bear
To add on to that solution, if you encrypt some data using a key that is stored, send that data to the client to then return to the server call. Then decrypt the data and see if it is what you expect (for instance, at least put an expiration ts in there (maybe 5 minutes into the future) so that someone doesn't just copy the data and post it to the function call to spam you. JWT could work in this scenario as well.
The data would be sent intially by the page and stored somewhere, then when it is doing the fetch call, it pulls that data and adds it to the body or a header (essentially becomes an auth token).