Next.js Discord

Discord Forum

Tips to make website more secure

Unanswered
Collin posted this in #help-forum
Open in Discord
Hello does anyone have some tips how to secure the website?

Also is it it better to do a post request to a custom api or let it do a function that is imported?

3 Replies

@Collin Hello does anyone have some tips how to secure the website? Also is it it better to do a post request to a custom api or let it do a function that is imported?
Turkish Van
Since all this stuff is pretty new, I would really appreciate if someone corrects me in case I am wrong.

In general, You should always prefer to fetch data and do all that stuff that contains some private info, such as Your super private API key, on the server.

In case You are on:
- Server Component, You can freely fetch the data directly
- Client Component, You can wrap that data fetch inside of Server Action and call it inside of Client Component

When talking about routes in Next.js 14, I might be wrong but I, myself, don't see a point in using API routes after the release of Server Actions unless it's used for some auth stuff, reading tokens etc.
Might be useful only in case You just really want to create an API so it can be used for something else or You just want to make Your backend independent of frontend.

It might be helpful to take a look at this blog post:
https://nextjs.org/blog/security-nextjs-server-components-actions
American Crow
Yeah agree mostly common use cases for a route handler are webhooks and mutating EXTERNAL data ( server actions only work within your next js app obviously)

A good safety practice is the package "server-only" so you don't accidentally expose endpoints via route handlers not via server actions nor via client imports.

And one more good safety practice is to have a server-utils and a client-utils. The server-utils having all your get data fetch calls in one file and again "sever-only" at the top. Prevents accidental imports to client / server actions