NextResponse.redirect wont work
Unanswered
Chinese perch posted this in #help-forum
Chinese perchOP
import { NextResponse } from "next/server";
import { connectToDb } from '@/utils/db'
import { redirect } from 'next/navigation'
const brcrypt = require('bcrypt')
export async function POST(req: Request): Promise<NextResponse> {
const res = await req.formData()
let enrno: string = String(res.get("enrno"));
let password: string = String(res.get("password"));
let con = connectToDb("rcampus")
con.connect((err: any) => {
if (err) throw err;
var sql = "SELECT * FROM users WHERE enrno=? ";
con.query(sql, [enrno], (err: any, result: any) => {
if (err) {
console.error("Error executing query:", err);
} else {
if ( brcrypt.compare(password, result[0]['password']) ) {
return NextResponse.redirect(process.env.DEV_URL+'/home')
}else{
console.log(brcrypt.compare(password, result[0]['password']))
}
}
});
});
// return new NextResponse("nice")
} NextResponse.redirect wont work10 Replies
Redirect only works when users directly open a
Also, if your client is sending an HTTP request via javascript like
It's recommended to use client-side navigation like
GET API endpoint in their browser, POST route handlers can't. Also, if your client is sending an HTTP request via javascript like
fetch instead of opening it in the browser, they won't be redirected due to security reasons (it is a standard)It's recommended to use client-side navigation like
router.push since Next.js can handle the cache for better performance. In native fetch API, there's a [rediect](https://developer.mozilla.org/en-US/docs/Web/API/Request/redirect) property that allows you to configure how redirects are handled.request.redirect in the code below?
import * as React from 'react';
import { Grid, TextField, FormControl, Button } from '@mui/material';
import { FormEvent, useState } from 'react';
export default function LoginPage() {
const [enrno, setEnrno] = useState('');
const [submitDisabled, setSubmitDisabled] = useState(true);
const isUsernameEmpty = enrno.trim() === '';
async function handleSubmit(e: FormEvent<HTMLFormElement>) {
e.preventDefault()
const formData = new FormData(e.target as HTMLFormElement);
const response = await fetch('/api/login', {
method: 'POST',
body: formData
}).then((value:Response)=>{
console.log(value)
})
}
return (
<Grid
container
spacing={0}
direction="column"
alignItems="center"
justifyContent="center"
sx={{ minHeight: '100vh' }}
>
<Grid item xs={3}>
<form onSubmit={handleSubmit} method='post'>
<FormControl>
<TextField
required
id="filled-required"
label="Enrollment No"
variant="filled"
sx={{minWidth: '300px',minHeight:'50px', mb: 2 }}
value={enrno}
onChange={(e) => { ...
</Button>
</FormControl>
</form>
</Grid>
</Grid>
);
}Chinese perchOP
?
No, it should be passed as an option. And please use
router.push insteadSince it’s a client component (or in Pages Router)
const router = useRouter()
router.push(“/the/pathâ€)@fuma No, it should be passed as an option. And please use `router.push` instead
Chinese perchOP
how do I pass this as an option though?
Like
fetch(“urlâ€, {
redirect: “your valueâ€
})You can read the mdn docs, it’s well-documented there