DEV Community

Tea Reggi
Tea Reggi

Posted on

2

Accessing request from any server component in Deno Fresh

Within Deno Fresh a route can have access to the request via an exported handler. What if you have a tree of components, and you'd like to access the request from any point in the tree?

The code below creates a request context and provider that you can use on all your pages.

export const handler: Handlers<Request> = {
  GET(request, ctx) {
    return ctx.render(request);
  },
  POST(request, ctx) {
    return ctx.render(request);
  },
  PUT(request, ctx) {
    return ctx.render(request);
  },
  DELETE(request, ctx) {
    return ctx.render(request);
  },
};

const RequestContext = createContext(new Request('http://localhost:8000/'));

export const useRequest = () => useContext(RequestContext);

export function withRequest(Component: () => JSX.Element) {
  return ({ data }: PageProps<Request>) => {
    return (
      <RequestContext.Provider value={data}>
        {<Component/>}
      </RequestContext.Provider>
    )
  }
}
Enter fullscreen mode Exit fullscreen mode

To use in your route:

import { handler, withRequest, useRequest } from "../lib/request";

export { handler }

const Greeting = () => {
  const { url } = useRequest()
  return <div>{url}</div>
}

export default withRequest(() => {
  return (
    <Greeting/>
  )
})
Enter fullscreen mode Exit fullscreen mode

AWS Q Developer image

Your AI Code Assistant

Automate your code reviews. Catch bugs before your coworkers. Fix security issues in your code. Built to handle large projects, Amazon Q Developer works alongside you from idea to production code.

Get started free in your IDE

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs