DEV Community

Composite
Composite

Posted on

A Some undocumented about Server Component on Next.js

The Server Component of Next.js is stateless component that it can get some request parameters: Headers and cookies.
But, There is no way to get other parameters such as request.url.

I don't understand why limited to get properties in Server Components. someone says you're not ready to use App Router yet.
I agree. Server component is future of React, but it's still experimental feature.

While I'm using App Router, I found a way of get some properties in server component, Let's get started.

What Header contains in Server Components?

I ran console.log() in a server component like below:

export const debugHeaders = () => {
  const list = headers();
  console.table(Array.from(list.entries()));
};
Enter fullscreen mode Exit fullscreen mode

And I found the following header key Let's see what it contains.

  • host: A real hostname of server. If you are using the app behind reverse proxy, do not use it.
  • x-forwarded-proto: A forwarded protocol of reverse proxy server. use it if you want check HTTPS behind reverse proxy.
  • x-forwarded-host: A forwarded real hostname behind a reverse proxy. use it if you are using the app behind reverse proxy.
  • x-middleware-invoke: It seems that show some infomation when proceed with middleware of Next.js.
  • x-invoke-path: A
  • x-invoke-query: A URL encoded query string with JSON. call DecodeURLComponent and JSON.parse If you want use.
  • x-invoke-output: Not sure what it is.

Depending on your server environment, the header key may be different, so be sure to extract and verify it yourself.

Get request.url and query string in Server Component

Based on the header information above, I made function to take in the URL and query string.

import { headers } from 'next/headers';

export const url = () => {
  const header = headers();
  return `${header.get('x-forwarded-proto') || (header.get('https') && 'https') || 'http'}://${header.get('x-forwarded-host') || header.get('host') || 'localhost:3000'}/${header.get('x-invoke-path')}`
}

export const query = () => {
  const header = headers();
  return JSON.parse(decodeURIComponent(header.get('x-invoke-query') || '{}')) as Record<string, string>
}
Enter fullscreen mode Exit fullscreen mode

Have fun and Happy Next.js'ing!

Top comments (0)