question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Fetching from own api route

See original GitHub issue

In Next.js if you had an api endpoint at ‘/pages/api/joke/’ inside of a page you can call:

const resp = await fetch('/api/joke')

and it will fetch the data that endpoint returns.

Is there already a simple way to do this in fresh? Because so far I have had to do this weird workaround with http request headers:

//routes/test.tsx

//Fetches from the example "joke" api endpoint\
//Inside GET in handler:
const url = 'http://' + req.headers.get('host')?.toString() + '/api/joke';
const resp = await fetch(url);

Is there a built in way to get the url of the project so you can easily call your own api endpoints within the app? (like the Next.js example)

Currently I have been working with a simple utility I made that basically just returns the url given a Request object, but if there was a baked in way this would be much easier

Issue Analytics

  • State:closed
  • Created a year ago
  • Reactions:2
  • Comments:5 (1 by maintainers)

github_iconTop GitHub Comments

5reactions
talebisinancommented, Sep 27, 2022

In the latest version, you can simply call the handler function defined in the API routes.

This is the joke.ts file comes with the example:

import { HandlerContext } from "$fresh/server.ts";

// Jokes courtesy of https://punsandoneliners.com/randomness/programmer-jokes/
const JOKES = [
  "Why do Java developers often wear glasses? They can't C#.",
  "A SQL query walks into a bar, goes up to two tables and says “can I join you?”",
  "Wasn't hard to crack Forrest Gump's password. 1forrest1.",
  "I love pressing the F5 key. It's refreshing.",
  "Called IT support and a chap from Australia came to fix my network connection.  I asked “Do you come from a LAN down under?”",
  "There are 10 types of people in the world. Those who understand binary and those who don't.",
  "Why are assembly programmers often wet? They work below C level.",
  "My favourite computer based band is the Black IPs.",
  "What programme do you use to predict the music tastes of former US presidential candidates? An Al Gore Rhythm.",
  "An SEO expert walked into a bar, pub, inn, tavern, hostelry, public house.",
];

export const handler = (_req: Request, _ctx: HandlerContext): Response => {
  const randomIndex = Math.floor(Math.random() * JOKES.length);
  const body = JOKES[randomIndex];
  return new Response(body);
};

You can simply access this API route by using it like;

import { Handlers, PageProps } from "$fresh/server.ts";
import { handler as jokeHandler } from "./api/joke.ts";

interface Joke {
  text: string;
}

export const handler: Handlers = {
  async GET(req, ctx) {
    const res = await jokeHandler(req, ctx);
    const joke = await res.text();
    return ctx.render(joke);
  },
};

export default function Foo({ data }: PageProps<Joke>) {
  return (
    <main>
      {data && <p>{data}</p>}
    </main>
  );
}

1reaction
alfuhigicommented, Jul 4, 2022

@WittySmirk did you use IS_BROWSER should work for client side

const resp = async () => {
    if (IS_BROWSER) {
      const resp = await fetch("/api/joke");
      const json = await resp.json();
      console.log(json);
    }
  };

it happen to my when I fetch some data in Nextjs in server side you should bring absolute url

Read more comments on GitHub >

github_iconTop Results From Across the Web

API Routes Details - Next.js
API Routes Details. Here is some essential information you should know about API Routes. Do Not Fetch an API Route from getStaticProps or...
Read more >
Internal API fetch with getServerSideProps? (Next.js)
It can be tempting to reach for an API Route when you want to fetch data from the server, then call that API...
Read more >
Fetch data from an API on the server-side with ... - Egghead.io
In this lesson, we will learn how to use getServerSideProps to dynamically fetch data and server-side render pages by consuming a "user profile"...
Read more >
Understanding how API routes work in Next.js
Let's break this code down - for an API route to work you need to export a function, that receives two parameters: request...
Read more >
API Routes for Next.js - Topcoder
API routing works similarly to page-based routing. The filename of an API is used to associate it with a route. Every API route...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found