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
check code
here's response
Avatar
dumbboy
Data.username === process.env.username If I'm not blind the env name is wrong.
Avatar
West African LionOP
huh
._.
bro
Avatar
dumbboy
Is it what I'm thinking
Avatar
West African LionOP
bro
solved
i lov u bro
and how im gonna direct it to a page :)
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
dumbboy
Didn't check, but NextResponse.redirect works right?
Avatar
dumbboy
@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
dumbboy
Why sorry? See you later
Avatar
West African LionOP
Thx
Avatar
West African LionOP
💗
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
server
client
Avatar
dumbboy
Where is request variable tho, isnt it req
@West African Lion
Avatar
West African LionOP
after doing changing requests to req something changed on terminal
Image
Avatar
dumbboy
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
dumbboy
Try to reload again.
Avatar
West African LionOP
can't i basically use window.location.href 🫠
Avatar
dumbboy
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
dumbboy
Okay, what is need of checking the process.env.varname.
Avatar
West African LionOP
i store my valid data to login to my dashboard
there are input fields
Image
Avatar
dumbboy
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
dumbboy
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
dumbboy
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
dumbboy
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
dumbboy
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
i have
Avatar
dumbboy
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
dumbboy
Okay, Close the forum once solved.
Avatar
West African LionOP
okay
@dumbboy
bro
so i must fetch the request to middleware file right?
Avatar
dumbboy
Yeah
Avatar
West African LionOP
bro in ts
what is the type of req?
string?
imo its string, just asking
Avatar
dumbboy
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
dumbboy
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
dumbboy
Wheare are you storing the login credentials, May I know.
Avatar
West African LionOP
.env
Avatar
dumbboy
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
dumbboy
You need to.
Avatar
West African LionOP
how to
Avatar
dumbboy
When logged in store you credentials in local storage or cookie then redirect to admin.
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
dumbboy
When Submit button is pressed.
Avatar
West African LionOP
what does options mean
Avatar
dumbboy
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
dumbboy
U are getting any errors?
Avatar
West African LionOP
no
Image
Avatar
dumbboy
It's getCookie("username")
Don't forget these ""
Avatar
West African LionOP
oh
Image
Image
Avatar
dumbboy
It's getCookie not getCookies
Avatar
West African LionOP
UGGHH
        getCookie("username") === process.env.name ? NextResponse.redirect(new URL('/admin', request.url)): ''

isnt it true
Avatar
dumbboy
WDYM
Avatar
West African LionOP
i still cant redirect
im gonna be back in 10mins im eating now
sry
Avatar
dumbboy
No worries
Avatar
West African LionOP
its been an hour
i forgot 💀
sry
Avatar
West African LionOP
@dumbboy
Avatar
dumbboy
I forgot too @West African Lion , How is it going
Avatar
West African LionOP
😄
i even forgot to eat
not good
the error still prerists
wbu
Avatar
dumbboy
Nothing, just doing company work
Avatar
West African LionOP
nice
Avatar
dumbboy
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
dumbboy
Okay, share the link
Avatar
dumbboy
Request Sent
you there?
Avatar
West African LionOP
sry
i was looking for ur req
@dumbboy
yo
i made u read & write
Avatar
dumbboy
Did you create middleware.ts
Avatar
West African LionOP
ya
in auth/
Avatar
dumbboy
Can you open any path starting with admin
Avatar
West African LionOP
@dumbboy
the hell
it worked
Avatar
dumbboy
Congratulations
Avatar
dumbboy
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
dumbboy
It's simple just follow me on vscode, I will do it.
Avatar
West African LionOP
ok
Avatar
dumbboy
Live Share sucks
Avatar
dumbboy
Can you check now
Avatar
West African LionOP
@dumbboyacc my req
Avatar
dumbboy
I helped him with middleware and cookies through vscode live share.
Answer