Next.js Discord

Discord Forum

redirecting from a route to a different one

Answered
West African Lion posted this in #help-forum
Open in Discord
Avatar
West African LionOP
I want to redirect to a different route using a server component
Answered by dumbboy
I helped him with middleware and cookies through vscode live share.
View full answer

190 Replies

Avatar
West African LionOP
i compare some input values to admin log in
and if the values are the same
i want to redirect
but idk how to do
i tried some methods but it returned errors
please help
Avatar
West African LionOP
import { NextResponse } from "next/server";

export async function POST(req) {
  try {
    const Data = await req.json();
    if (Data.username === process.env.username) {
      console.log("uwu");
    } else {
      console.log("now uwu");
    }
    console.log(Data.username, 'data');
    console.log(process.env.name, 'env');

    return NextResponse.json({ status: 201 });
  } catch (error) {
    return NextResponse.json({
      message: "An error occurred while logging in",
      status: 500,
    });
  }
}
.env
name=scopedevadmin
password=accessadmin1
response:
Image
api actually
but
im doing a comparison here
idk why but the values arent same
it must be
but it isnt
Avatar
@West African Lion response:
Avatar
West African LionOP
here's response
Avatar
West African LionOP
huh
._.
bro
Avatar
Is it what I'm thinking
Avatar
West African LionOP
bro
solved
Avatar
@dumbboy Is it what I'm thinking
Avatar
West African LionOP
i lov u bro
and how im gonna direct it to a page :)
Original message was deleted
Avatar
West African LionOP
no
i ned ur help too
actually
ive used it before
ya
import { NextResponse } from "next/server";
import { redirect } from 'next/navigation'


export async function POST(req) {
  try {
    const Data = await req.json();
    if (Data.username === process.env.name) {
      console.log("uwu");
      redirect('https://nextjs.org/');

    } else {
      console.log("now uwu");
    }
    return NextResponse.json({ status: 201 });
  } catch (error) {
    return NextResponse.json({
      message: "An error occurred while logging in",
      status: 500,
    });
  }
}
Avatar
Didn't check, but NextResponse.redirect works right?
Avatar
@West African Lion Are you there?
Avatar
West African LionOP
Im really sry
Im going to school
Im gonna be back in 2hrs
Sry
Avatar
Why sorry? See you later
Avatar
West African LionOP
Thx
Avatar
West African LionOP
💗
Original message was deleted
Avatar
West African LionOP
its not working
import { NextResponse } from "next/server";
import { redirect } from "next/navigation";

export async function POST(req) {
  try {
    const Data = await req.json();
    if (Data.username === process.env.name) {
      console.log("uwu");
      const loginUrl = new URL("/admin", request.url);
      loginUrl.searchParams.set("from", request.nextUrl.pathname);
      return NextResponse.redirect(loginUrl);
    } else {
      console.log("now uwu");
    }
    // Given an incoming request...

  } catch (error) {
    return NextResponse.json({
      message: "An error occurred while logging in",
      status: 500,
    });
  }
}
Image
Image
Avatar
@West African Lion Click to see attachment
Avatar
West African LionOP
server
Avatar
@West African Lion Click to see attachment
Avatar
West African LionOP
client
Avatar
Where is request variable tho, isnt it req
@West African Lion
Avatar
@dumbboy Where is `request` variable tho, isnt it `req`
Avatar
West African LionOP
after doing changing requests to req something changed on terminal
Image
Avatar
Okay, is it working as expected
Also remove redirect import from next/navigation It isn't required.
Avatar
West African LionOP
but route isnt changed
Avatar
Try to reload again.
Avatar
West African LionOP
can't i basically use window.location.href 🫠
Avatar
@West African Lion can't i basically use window.location.href 🫠
Avatar
Till now I didn't understand, what you are trying to do exactly.

Can you explain.
Avatar
West African LionOP
still isnt working
bro
i am trying to do an admin page to my portfolio website to manage blogs
Image
here's my structure
i use api/admin/route.js beacuse i can't access process.env.varname in a client component
Avatar
Okay, what is need of checking the process.env.varname.
Avatar
West African LionOP
i store my valid data to login to my dashboard
Avatar
@dumbboy Okay, what is need of checking the process.env.varname.
Avatar
West African LionOP
there are input fields
Image
Avatar
Okay, you are trying to check if admin is logged in or not before allowing him to go to that page.

Am I right?
Avatar
West African LionOP
ya ya
Avatar
so, you have stored username and password in env that should match the logged in data?
Avatar
West African LionOP
and i want to store a boolean data that has a value of "isLoggedIn"
yes, actually
as you can see on my console
the login data and the data on .env file do match
uwu is printed on my console
Avatar
Why don't you stop him at sign in, store some cookie isLoggedIn if the user entered right credentials, else show Invalid Credentials.
Did you understand?
Avatar
West African LionOP
now the main problem is redirecting to a different route
Avatar
@West African Lion now the main problem is redirecting to a different route
Avatar
You are not supposed to write redirection in api, you directly need to write in page.
Avatar
West African LionOP
but im comparing the data on api
Avatar
You can/should use middleware, Do you have live server in vscode.
Api is called at /api but you want to restrict /admin routes. Right?
Avatar
West African LionOP
ya
Avatar
Can you send the live share link, I can help you.
Avatar
West African LionOP
i think i got it
i can solve it using docs
Avatar
@West African Lion i think i got it
Avatar
Okay, Close the forum once solved.
Avatar
West African LionOP
okay
@dumbboy
bro
so i must fetch the request to middleware file right?
Avatar
Yeah
Avatar
West African LionOP
bro in ts
what is the type of req?
string?
imo its string, just asking
Avatar
Nope, I thinks it's NextRequest, just lemme check reql quick.
Avatar
West African LionOP
i just saw it on docs
thx
but i must read about the 'matcher'
Avatar
Yeah, it's just basic, you will be able to figure it out.
Avatar
West African LionOP
where is the problem
Image
import { NextResponse } from 'next/server'
import type { NextRequest } from 'next/server'
 
// This function can be marked `async` if using `await` inside
export async function middleware(request: NextRequest) {
    console.log('hello')
    try {
        const Data = await request.json();
        if (Data.username === process.env.name) {
          console.log("uwu");
          const loginUrl = new URL("/admin", request.url);
          loginUrl.searchParams.set("from", request.nextUrl.pathname);
          return NextResponse.redirect(loginUrl);
        } else {
          console.log("now uwu");
        }
      } catch (error) {
        return NextResponse.json({
          message: "An error occurred while logging in",
          status: 500,
        });
      }
  return NextResponse.redirect(new URL('/admin', request.url))
}
 
export const config = {
  matcher: '/auth/:path*',
}
Avatar
Wheare are you storing the login credentials, May I know.
Avatar
West African LionOP
.env
Avatar
@West African Lion .env
Avatar
I mean the login credentials, if you are logged in you need to know right, so you need to use localstorage or cookies.
Avatar
West African LionOP
i didnt use it
but i need
Avatar
@West African Lion but i need
Avatar
You need to.
Avatar
West African LionOP
how to
Avatar
When logged in store you credentials in local storage or cookie then redirect to admin.
Avatar
@dumbboy When logged in store you credentials in local storage or cookie then redirect to admin.
Avatar
Then In middleware check if the credentials stored in local storage/cookie matches the .env or not.
Hope you understood.
Avatar
West African LionOP
bro
i can't
where should i set the cookies
Avatar
@West African Lion where should i set the cookies
Avatar
When Submit button is pressed.
Avatar
@dumbboy When Submit button is pressed.
Avatar
West African LionOP
what does options mean
Avatar
@West African Lion what does options mean
Avatar
U can setup max age, for how long the cookie will be active.
Avatar
West African LionOP
i get undefined whey i try to log it on console
      console.log(username)
      setCookie('username', username)
      setCookie('password', password)
      console.log(getCookie(username))
Avatar
U are getting any errors?
Avatar
West African LionOP
no
Image
Avatar
It's getCookie("username")
Don't forget these ""
Avatar
West African LionOP
oh
Image
Image
Avatar
It's getCookie not getCookies
Avatar
West African LionOP
UGGHH
Avatar
@dumbboy It's getCookie not getCookies
Avatar
West African LionOP
        getCookie("username") === process.env.name ? NextResponse.redirect(new URL('/admin', request.url)): ''

isnt it true
Avatar
West African LionOP
i still cant redirect
im gonna be back in 10mins im eating now
sry
Avatar
No worries
Avatar
@dumbboy No worries
Avatar
West African LionOP
its been an hour
i forgot 💀
sry
Avatar
West African LionOP
@dumbboy
Avatar
@West African Lion <@839454110302732309>
Avatar
I forgot too @West African Lion , How is it going
Avatar
West African LionOP
😄
i even forgot to eat
Avatar
@dumbboy I forgot too <@906233193609453572> , How is it going
Avatar
West African LionOP
not good
the error still prerists
Avatar
@dumbboy I forgot too <@906233193609453572> , How is it going
Avatar
West African LionOP
wbu
Avatar
@West African Lion wbu
Avatar
Nothing, just doing company work
Avatar
West African LionOP
nice
Avatar
I forgot to mention to get cookie in server side you need to pass res,req in options
or, you can just use request.cookies.get("username")
can you try this once
If you are still doing the project
Avatar
West African LionOP
bro
live server
no more thing
i cant do it
share*
Avatar
Okay, share the link
Avatar
Request Sent
you there?
Avatar
West African LionOP
sry
i was looking for ur req
@dumbboy
yo
i made u read & write
Avatar
Did you create middleware.ts
Avatar
West African LionOP
ya
in auth/
Avatar
Can you open any path starting with admin
Avatar
West African LionOP
@dumbboy
the hell
it worked
Avatar
Congratulations
Avatar
you there?
Avatar
West African LionOP
@dumbboyim back
lemme read
@dumbboybro actually im really new at next.js
and i don't know a lot how to do what you said
Avatar
It's simple just follow me on vscode, I will do it.
Avatar
West African LionOP
ok
Avatar
Live Share sucks
Avatar
Can you check now
Avatar
West African LionOP
@dumbboyacc my req
Avatar
I helped him with middleware and cookies through vscode live share.
Answer