Next.js Discord

Discord Forum

How can i secure routes?

Answered
Brown bear posted this in #help-forum
Open in Discord
Original message was deleted.
Answered by aardani
// page.tsx or layout.tsx
const session = await getAuth()
if(session) return <>Hello World</>
if(!sessin) redirect('/login')
View full answer

36 Replies

Original message was deleted
which route are you trying to secure? is it a page.tsx or a route.ts
you can secure them by checking the necesssary checks first before rendering the page or processing the data
Brown bear
its a page.tsx
sorry if i seem dumb cause im new
// page.tsx or layout.tsx
const session = await getAuth()
if(session) return <>Hello World</>
if(!sessin) redirect('/login')
Answer
you can also protect them via next.js's edge middleware
@aardani tsx // page.tsx or layout.tsx const session = await getAuth() if(session) return <>Hello World</> if(!sessin) redirect('/login')
Brown bear
alright thanks, so i already have a working login that fetches from the backend already and i've also stored it into redux store.
so basically the response of the login action that i would receive is:

{
    "status": 200,
    "message": "Success",
    "token": "eyJhbGciOiJIUzUxMiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiJkaGlyb2phcEBnbWFpbC5jb20iLCJlbWFpbCI6ImRoaXJvamFwQGdtYWlsLmNvbSIsIm5iZiI6MTcwMTYxMTI4MywiZXhwIjoxNzAxNjEzMDgzLCJpYXQiOjE3MDE2MTEyODMsImlzcyI6Iklzc3VlciIsImF1ZCI6IkF1ZGllbmNlIn0.ZUBj7qX1YqIKJoFUQnXbmSPvQbe41yVga9OMuBfvw355_DuyykGMxrNY67pkq2fiOWrs0UghnllJzpvGapp8bQ",
    "tokenExpiration": "2023-12-03T14:18:03.4132094Z",
    "user": {
        "id": "bc98dbe6-ae32-48c1-a05a-b55c3e17898b",
        "name": "User1",
        "phoneNumber": "0818693080",
        "email": "user1@gmail.com",
        "gender": "Male",
        "birthdate": "2023-12-02T00:00:00"
    }
}


ive stored it like this:

interface User {
  id: string;
  name: string;
  phoneNumber: string;
  email: string;
  gender: string;
  birthdate: string;
}

interface UserState {
  user: User | null;
  token: string | null;
  isAuthenticated: boolean;
  tokenExpiration: Date | null;
}

const initialState: UserState = {
  user: null,
  token: null,
  isAuthenticated: false,
  tokenExpiration: null,
};

but i dont really know how can i utilize the token, could u help me?
@aardani After loging in with the user, set the token in a secure cookie.
Brown bear
how can i do that tho?
That way, you do auth checks at the server and not in the client to reduce waterfall effect
@aardani Then you can check and validate the cookie for every request to the server
Brown bear
hmm i dont really understand this
@Brown bear how can i do that tho?
Set cookie using cookies().set('auth', token)
Get cookie using cookies().get('auth')
Check the docs
@Brown bear whats waterfall effect?
Like how you make multiple roundtrips in the client to fetch data at first page load instead of getting everything ready at the server then passing it to the browser
I cant help if u dont specify which part you dont understand
@aardani Which part?
Brown bear
"for every request to the server"
Dont you want to secure routes?
Brown bear
yeah i want to
If you want to secure routes then you have to check every request to the server no?
For that particular route
Brown bear
oh so what that request to server means like accessing a certain page?
i dont really understand the terms you use sorry haha
Yess but not only that, but stuff like fetch to Next.js route.ts, or Server Actions.

Basically any server environment
No need to say sorry, just clarify what you dont understand. No pressure we've all been there
You can check user cookie first (and preferably validate them) before returning components or do other stuff
Brown bear
wehhh kak baru liat profilenya alumni binus ya wkwkwk
Yeah
Better use english soalnya ini server publik
Also this post is also shown in nextjs-forum.com :p
Brown bear
damn okok
You can dm me if you need clarication in bahasa, as a perk of finding me here.