redirecting from a route to a different one
Answered
West African Lion posted this in #help-forum

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.
190 Replies

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

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:

api actually
but
im doing a comparison here
idk why but the values arent same
it must be
but it isnt

@West African Lion response:

West African LionOP
here's response

@West African Lion js
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,
});
}
}

Data.username === process.env.username
If I'm not blind the env name is wrong.
West African LionOP
huh
._.
bro

Is it what I'm thinking

West African LionOP
bro
solved

@dumbboy Is it what I'm thinking

West African LionOP
i lov u bro
and how im gonna direct it to a page :)
Original message was deleted

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,
});
}
}

Didn't check, but
NextResponse.redirect
works right?
@West African Lion Are you there?

West African LionOP
Im really sry
Im going to school
Im gonna be back in 2hrs
Sry

Why sorry? See you later

West African LionOP
Thx

West African LionOP
💗
Original message was deleted

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,
});
}
}



@West African Lion Click to see attachment

West African LionOP
server

@West African Lion Click to see attachment

West African LionOP
client

Where is
request
variable tho, isnt it req
@West African Lion

@dumbboy Where is `request` variable tho, isnt it `req`

West African LionOP
after doing changing requests to req something changed on terminal


Okay, is it working as expected
Also remove redirect import from
next/navigation
It isn't required.
West African LionOP
but route isnt changed

Try to reload again.

West African LionOP
can't i basically use window.location.href ðŸ«

@West African Lion can't i basically use window.location.href ðŸ«

Till now I didn't understand, what you are trying to do exactly.
Can you explain.
Can you explain.

West African LionOP
still isnt working
bro
i am trying to do an admin page to my portfolio website to manage blogs

here's my structure
i use api/admin/route.js beacuse i can't access process.env.varname in a client component

Okay, what is need of checking the process.env.varname.

West African LionOP
i store my valid data to login to my dashboard

@dumbboy Okay, what is need of checking the process.env.varname.

West African LionOP
there are input fields


Okay, you are trying to check if admin is logged in or not before allowing him to go to that page.
Am I right?
Am I right?

West African LionOP
ya ya

so, you have stored username and password in env that should match the logged in data?

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

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?

West African LionOP
now the main problem is redirecting to a different route

@West African Lion now the main problem is redirecting to a different route

You are not supposed to write redirection in api, you directly need to write in page.

West African LionOP
but im comparing the data on api

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?
West African LionOP
ya

@dumbboy You can/should use middleware, Do you have live server in vscode.

West African LionOP
i have

Can you send the live share link, I can help you.

West African LionOP
i think i got it
i can solve it using docs

@West African Lion i think i got it

Okay, Close the forum once solved.

West African LionOP
okay
@dumbboy
bro
so i must fetch the request to middleware file right?

Yeah

West African LionOP
bro in ts
what is the type of req?
string?
imo its string, just asking

Nope, I thinks it's NextRequest, just lemme check reql quick.

West African LionOP
i just saw it on docs
thx
but i must read about the 'matcher'

Yeah, it's just basic, you will be able to figure it out.

West African LionOP
where is the problem

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*',
}

Wheare are you storing the login credentials, May I know.

West African LionOP
.env

@West African Lion .env

I mean the login credentials, if you are logged in you need to know right, so you need to use localstorage or cookies.

West African LionOP
i didnt use it
but i need

@West African Lion but i need

You need to.

West African LionOP
how to

When logged in store you credentials in local storage or cookie then redirect to admin.

@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.

West African LionOP
bro
i can't
where should i set the cookies

@West African Lion where should i set the cookies

When Submit button is pressed.

@dumbboy When Submit button is pressed.

West African LionOP
what does options mean

@West African Lion what does options mean

U can setup max age, for how long the cookie will be active.

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))

U are getting any errors?

West African LionOP
no


It's
getCookie("username")
Don't forget these
""

West African LionOP
oh



It's getCookie not getCookies

West African LionOP
UGGHH

@dumbboy It's getCookie not getCookies

West African LionOP
getCookie("username") === process.env.name ? NextResponse.redirect(new URL('/admin', request.url)): ''
isnt it true

West African LionOP
i still cant redirect
im gonna be back in 10mins im eating now
sry

No worries

West African LionOP
@dumbboy

@West African Lion <@839454110302732309>

I forgot too @West African Lion , How is it going

West African LionOP
😄
i even forgot to eat

@dumbboy I forgot too <@906233193609453572> , How is it going

West African LionOP
not good
the error still prerists

@dumbboy I forgot too <@906233193609453572> , How is it going

West African LionOP
wbu

@West African Lion wbu

Nothing, just doing company work

West African LionOP
nice

I forgot to mention to get cookie in server side you need to pass
res,req
in optionsor, you can just use
request.cookies.get("username")
can you try this once
If you are still doing the project

West African LionOP
bro
live server
no more thing
i cant do it
share*

Okay, share the link

Request Sent
you there?

West African LionOP
sry
i was looking for ur req
@dumbboy
yo
i made u read & write

Did you create
middleware.ts

West African LionOP
ya
in auth/

Can you open any path starting with admin

West African LionOP
@dumbboy
the hell
it worked

Congratulations

you there?

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

It's simple just follow me on vscode, I will do it.

West African LionOP
ok

Live Share sucks

Can you check now

West African LionOP
@dumbboyacc my req

I helped him with middleware and cookies through vscode live share.
Answer