Possible to redirect '/' to '/?a=b' on the server, NOT on the client?
Answered
Asian black bear posted this in #help-forum
Asian black bearOP
It works with:
but would it be possible to redirect with such a query param a bit before? like not on the client?
As of (this)[https://nextjs.org/docs/app/api-reference/next-config-js/redirects]:
I restart the dev server (next dev), it says compiled client and server successfully, no error messages, while on the browser I get the image^.
I'm a beginner, so it might be something basic but I can't figure it out.
const router = useRouter();
useEffect(() => {
router.push(`/?b=true`);
}, []);but would it be possible to redirect with such a query param a bit before? like not on the client?
As of (this)[https://nextjs.org/docs/app/api-reference/next-config-js/redirects]:
/** @type {import('next').NextConfig} */
const nextConfig = {
async redirects() {
return [{ source: "/", destination: "/?b=true", permanent: false }];
},
compiler: {
styledComponents: true,
},
};
module.exports = nextConfig;I restart the dev server (next dev), it says compiled client and server successfully, no error messages, while on the browser I get the image^.
I'm a beginner, so it might be something basic but I can't figure it out.
Answered by Asian black bear
1 of 1 unhandled error
Server Error
Error: URL is malformed "/?b=true". Please use only absolute URLs - https://nextjs.org/docs/messages/middleware-relative-urls
This error happened while generating the page. Any console logs will be displayed in the terminal window.
Source
middleware.ts (12:24) @ redirect
10 | // console.log(resp);
11 | // resp.url = '/?b=true';
13 | }
14 |
15 | return NextResponse.next();
Server Error
Error: URL is malformed "/?b=true". Please use only absolute URLs - https://nextjs.org/docs/messages/middleware-relative-urls
This error happened while generating the page. Any console logs will be displayed in the terminal window.
Source
middleware.ts (12:24) @ redirect
10 | // console.log(resp);
11 | // resp.url = '/?b=true';
12 | return NextResponse.redirect("/?b=true");| ^
13 | }
14 |
15 | return NextResponse.next();
61 Replies
Asian black bearOP
tried
also this:
async rewrites() {
return [
{
source: "/",
destination: "/?b=true",
has: [
{
type: "query",
key: "b",
value: "true",
},
],
},
];
},
but unless i have the useEffect with router.push() i can't do anything.
rewrites too with the same array. maybe i'm doing something wrong.also this:
async rewrites() {
return [
{
source: "/",
destination: "/?b=true",
has: [
{
type: "query",
key: "b",
value: "true",
},
],
},
];
},
but unless i have the useEffect with router.push() i can't do anything.
its because
/?b=true is still /, so it is an infinite loop...you could use middlewire and look at the query param, and if not set, then redirect
wait, after reading the [rewrites](https://nextjs.org/docs/app/api-reference/next-config-js/rewrites#header-cookie-and-query-matching) docs, i think if you omit the value, then it might redirect only if
b is not present@riský wait, after reading the [rewrites](<https://nextjs.org/docs/app/api-reference/next-config-js/rewrites#header-cookie-and-query-matching>) docs, i think if you omit the value, then it might redirect only if `b` is not present
Asian black bearOP
i'm sorry i don't understand. i've never written a middleware before. i tried doing this but nothing happens. i don't get it why the console log doesn't even run...
import type { NextRequest } from "next/server";
import { NextResponse } from "next/server";
export function middleware(req: NextRequest) {
const { searchParams } = req.nextUrl;
console.log("hi"); // -> doesn't show
// console.log(req.nextUrl.pathname); // -> doesn't give me anything
if (!searchParams.get("b")) {
return NextResponse.rewrite(new URL("/?b=true", req.url));
}
return NextResponse.next();
}
export const config = {
matcher: "/",
};@DirtyCajunRice | AppDir the has is what breaks this.
Asian black bearOP
i have since commented out everything in my next.config.js related to this, besides compiler - styled components.
i placed the middleware in app's root (not using an src folder)
@Asian black bear i have since commented out everything in my next.config.js related to this, besides compiler - styled components.
thats good. the middleware is the right way to do it anyway
@Asian black bear i placed the middleware in app's root (not using an src folder)
did you restart the dev server
wait
Asian black bearOP
yes, many times, on all tries
its /app/middleware.ts?
@DirtyCajunRice | AppDir its /app/middleware.ts?
Asian black bearOP
i don't know what a working middleware should be at. yes that's where it's at.
take it out of the apo dir. it goes top level
Asian black bearOP
i know the documentation says not to put it there. but where else should i put it?
okay
then restart the dev server
you should see your hi
Asian black bearOP
ok wow i actually saw it
so then how can i add ?b=true to the url?
@DirtyCajunRice | AppDir you should see your hi
Asian black bearOP
thanks for that!
@Asian black bear so then how can i add ?b=true to the url?
So you need to check and make sure that it doesnt already have the param
not rewrite tho
you are good until the rewrite line. thats where you messed up
Asian black bearOP
if the request comes in and it has the param, i want to let it through as is. if it comes in and it doesn't, i want to add it as true.
const resp = NextResponse.next();
resp.url.searchParams.add("b", "seksay");
return resp;something like that
inside your if
Asian black bearOP
i did it with resp.url.searchParams and resp.searchParams but there's no searchParams in there. I logged the resp object out:
do i just rewrite the url like
?
{
cookies: ResponseCookies {},
url: '',
body: null,
bodyUsed: false,
headers: { x-middleware-next: '1' },
ok: true,
redirected: false,
status: 200,
statusText: '',
type: 'default'
}do i just rewrite the url like
resp.url = '/?b=true'?
can't assign, it's a read-only property
@Asian black bear can't assign, it's a read-only property
ah. Thats right. Redirect. not rewrite
return NextResponse.redirect("http://localhost:3000/?b=poo")
@DirtyCajunRice | AppDir return NextResponse.redirect("http://localhost:3000/?b=poo")
Asian black bearOP
1 of 1 unhandled error
Server Error
Error: URL is malformed "/?b=true". Please use only absolute URLs - https://nextjs.org/docs/messages/middleware-relative-urls
This error happened while generating the page. Any console logs will be displayed in the terminal window.
Source
middleware.ts (12:24) @ redirect
10 | // console.log(resp);
11 | // resp.url = '/?b=true';
13 | }
14 |
15 | return NextResponse.next();
Server Error
Error: URL is malformed "/?b=true". Please use only absolute URLs - https://nextjs.org/docs/messages/middleware-relative-urls
This error happened while generating the page. Any console logs will be displayed in the terminal window.
Source
middleware.ts (12:24) @ redirect
10 | // console.log(resp);
11 | // resp.url = '/?b=true';
12 | return NextResponse.redirect("/?b=true");| ^
13 | }
14 |
15 | return NextResponse.next();
Answer
and add it to make the full url
Asian black bearOP
with this:
i'm getting asked in the browser (pic) and no matter what i go with it doesn't result to anything
export function middleware(req: NextRequest) {
const { searchParams } = req.nextUrl;
console.log("hi");
if (!searchParams.get("b")) {
console.log(req.nextUrl.host);
return NextResponse.redirect(`${req.nextUrl.host}?b=true`);
}
return NextResponse.next();
}i'm getting asked in the browser (pic) and no matter what i go with it doesn't result to anything
it doesnt have the protocol on its own iirc
Asian black bearOP
i added / before ? and i get the same reaction
@Asian black bear Click to see attachment
you are missing protocol
Asian black bearOP
return NextResponse.redirect(new URL("/?b=true", req.url));rewrite is not what you want
Asian black bearOP
it worked with this.
oh good
Asian black bearOP
hitting localhost:3000 brings it in with the query param added. i've been on this for 2 days
i appreciate your help!
Asian black bearOP
i was sure it could be done on the server side as well. i take it it's faster to do it this way than on the client, right? tell me it was worth the trouble.
@DirtyCajunRice | AppDir return NextResponse.redirect("http://localhost:3000/?b=poo")
this is the answer then. you just decided to format the url a bit
edited to have the host
@Asian black bear i was sure it could be done on the server side as well. i take it it's faster to do it this way than on the client, right? tell me it was worth the trouble.
yes middleware is the first thing thats hit. so its the fastest
Asian black bearOP
i checked the link to the documentation it gave me:
https://nextjs.org/docs/messages/middleware-relative-urls
and tried it out and it worked (so very few things worked when i started to try things form the doc)
https://nextjs.org/docs/messages/middleware-relative-urls
and tried it out and it worked (so very few things worked when i started to try things form the doc)
so middleware
1. is on the way from the client's url request to the server, but it hasn't reached the server yet,
2. or it has, but on the middle way backwards towards the client it populates the url bar with the query param
which one?
1. is on the way from the client's url request to the server, but it hasn't reached the server yet,
2. or it has, but on the middle way backwards towards the client it populates the url bar with the query param
which one?
wow i'm so happy
1 is correct
Asian black bearOP
so this being the home page, this will not be valid for any other endpoint, just the home page, right?
Asian black bearOP
thank you very much!!!