You have a Server Component that imports next/router. Use next/navigation instead.
Answered
Pigeon tremex posted this in #help-forum
Pigeon tremexOP
If I want to travel to a certain page from server then how can I do it? Like as soon as login happens (validated from dashboard) the go to dashboard. The only way I have in mind is to make the server send a response and then read the response from client and then navigate. But is there any method where I can navigate directly from the server side ?
35 Replies
Pigeon tremexOP
I also did
but it does not redirect instead shows timeout error
NextResponse.redirect(new URL("/dashboard"));but it does not redirect instead shows timeout error
// useRouter
import { useRouter } from 'next/navigation'
const router = useRouter()
router.push('/dashboard')referral : https://nextjs.org/docs/app/building-your-application/routing/linking-and-navigating#disabling-scroll-restoration
@Rain infotech javascript
// useRouter
import { useRouter } from 'next/navigation'
const router = useRouter()
router.push('/dashboard')
referral : https://nextjs.org/docs/app/building-your-application/routing/linking-and-navigating#disabling-scroll-restoration
Pigeon tremexOP
Yeah but I want to redirect from the server, is it possible? It says useRouter canot be used in server
@Pigeon tremex Yeah but I want to redirect from the server, is it possible? It says useRouter canot be used in server
use redirect() if you want to redirect fromt he server
@Pigeon tremex I also did
js
NextResponse.redirect(new URL("/dashboard"));
but it does not redirect instead shows timeout error
this should works, but this is for route.ts
Answer
@aardani this should works, but this is for route.ts
Pigeon tremexOP
ohh oohh oki, Thanks
@aardani this should works, but this is for route.ts
Pigeon tremexOP
It just shows something like this like, Temporary redirect and then it doesn't actually redirect.
Where did I go wrong ?
export const POST=async (request:NextRequest):Promise<any>=>{
try{
const requestBody=await request.json();
const response=await registerUser(requestBody);
console.log(new URL('/',request.url));
return NextResponse.redirect(new URL('/',request.url))
}
catch(err:any){
return NextResponse.json({message:err.message},{status:StatusCodes.BAD_REQUEST})
}
} Where did I go wrong ?
but in middleware.ts the NextResponse.redirect just works fine
just in my own route it doesn't
🥲
did
new URL gets console logged?@aardani did `new URL` gets console logged?
Pigeon tremexOP
URL {
href: 'http://localhost:3000/',
origin: 'http://localhost:3000',
protocol: 'http:',
username: '',
password: '',
host: 'localhost:3000',
hostname: 'localhost',
port: '3000',
pathname: '/',
search: '',
searchParams: URLSearchParams {
size: 0,
Symbol(query): [],
Symbol(context): URL {...}
},
hash: '',
Symbol(context): URLContext {
href: 'http://localhost:3000/',
protocol_end: 5,
username_end: 7,
host_start: 7,
host_end: 16,
pathname_start: 21,
search_start: 4294967295,
hash_start: 4294967295,
port: 3000,
scheme_type: 0
},
Symbol(query): URLSearchParams {
size: 0,
Symbol(query): [],
Symbol(context): URL {...}
}
}This is the console
did you call this route via the client?
Pigeon tremexOP
umm.. like how? I mean shouldn't the NextResponse.redirect directly take me to that page ?
try using redirect() from 'next/navigation' instead
well i havent tried using NextResponse.redirect ðŸ«
but i have used a lot of redirect() in server actions before
works wonderfully
Pigeon tremexOP
ohh ohh oki, lemme give it a try then 😅
redirect should also work in route handler
but can i see how you call this route in the front end?
@aardani but can i see how you call this route in the front end?
Pigeon tremexOP
"use client"
import { API_URL } from "../../../../API/globals/url";
export const universalPost = async (data:any,url:string,identifier:number) => {
const requestOptions = {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(data)
};
const fullUrl=`${API_URL}${url}`
try {
await fetch(fullUrl, requestOptions);
} catch (error) {
console.error('Error:', error);
}
}"use client"
import { useState } from "react";
import { universalPost } from "../apiConnectors/system/POST";
import Link from "next/link";
import "./loginAndRegister.css";
export const Register=()=>{
const [name,setName]=useState("");
const [email,setEmail]=useState("");
const [password,setPassword]=useState("");
const registerUser=async (e:any)=>{
e.preventDefault();
const body={
name:name,
email:email,
password:password
}
await universalPost(body,"/register",0);
}
return(
<form onSubmit={(e)=>registerUser(e)} className="loginAndRegisterForm">
<input type="text" placeholder="Name" onChange={(e)=>setName(e.target.value)}/><br/>
<input type="text" placeholder="Email" onChange={(e)=>setEmail(e.target.value)}/><br/>
<input type="password" placeholder="Password" onChange={(e)=>setPassword(e.target.value)}/><br/>
<button type="submit"> Register </button>
<h1> Already have an account? <Link href="/login" className=" text-red-400"> Login </Link> </h1>
</form>
)
}
export default Register;like this
Pigeon tremexOP
Yeah, can't figure out what's the issuewell
This works
so im guessing its the limitation of the fetch() function
Pigeon tremexOP
ohh ohh oki, lemme give it a try
Thai
have you found a workaround?
Original message was deleted
This is a different problem than the original query. Please make a new help forum