Next.js Discord

Discord Forum

Is encoding an object into the url is a good idea?

Unanswered
Maltese posted this in #help-forum
Open in Discord
Avatar
MalteseOP
Hello, guys! I want to ask, about my app that I am building. Its a fullstack blog app and I am doing it with educational purposes, to see how fullstack apps are build. And today I met a case study. Its about my /posts query with searchParams to my server where I perform database requests based on the searchParams I've recived. And I want to keep the queries to my server generic, that means, no hard coded values like ?search=Hello&orderBy=asc I want to pass it a whole Prisma.PostFindManyArgs object into my query like /posts?query=URIEncoded(obj) and I did it and it works very good I like it, its clean and flexible solution, but this mean that now my route looks like this
export async function GET(req: NextRequest) {
  const searchParams = req.nextUrl.searchParams;

  const query = searchParams.get('query');

  try {
    const posts = await PostRepo.findMany({
      include: {
        author: true,
        tags: true,
        comments: {
          include: {
            author: true,
          },
        },
      },
      ...(query ? JSON.parse(query) : {}),
    });
    return NextResponse.json(posts, { status: 200 }); // 200 OK
  } catch (error) {
    const message = getErrorMessage(error);
    console.error('Error occurred while fetching posts:', error);
    return NextResponse.json(
      { error: 'Failed to fetch posts: ' + message },
      { status: 500 } // 500 Internal Server Error
    );
  }
}

And this means that everbody can just change the query params like Get posts and include author email, passowrd, phone number and etc. It will look like
 const { data } = useGetPostsQuery({ include: {author: {email, password, phonenum }} });

You get the idea. And I want to ask, how to proceed now? The only thing that come to my mind is to create a query allow list, so only allowed queries can be make. And also is this approach with encoding a obj into the url is a good idea or there is a better way? I want to protect from sql inj

0 Replies